从视图模型将焦点放在WPF中的TextBox上


129

我认为a TextBox和a Button

现在,我在单击按钮时检查条件,如果条件结果为假,则向用户显示消息,然后将光标设置到TextBox控件。

if (companyref == null)
{
    var cs = new Lipper.Nelson.AdminClient.Main.Views.ContactPanels.CompanyAssociation(); 

    MessageBox.Show("Company does not exist.", "Error", MessageBoxButton.OK,
                    MessageBoxImage.Exclamation);

    cs.txtCompanyID.Focusable = true;

    System.Windows.Input.Keyboard.Focus(cs.txtCompanyID);
}

上面的代码在ViewModel中。

CompanyAssociation是视图名称。

但是光标没有在中设置TextBox

xaml是:

<igEditors:XamTextEditor Name="txtCompanyID" 
                         KeyDown="xamTextEditorAllowOnlyNumeric_KeyDown"
                         ValueChanged="txtCompanyID_ValueChanged"
                         Text="{Binding Company.CompanyId,
                                        Mode=TwoWay,
                                        UpdateSourceTrigger=PropertyChanged}"
                         Width="{Binding ActualWidth, ElementName=border}"
                         Grid.Column="1" Grid.Row="0"
                         VerticalAlignment="Top"
                         HorizontalAlignment="Stretch"
                         Margin="0,5,0,0"
                         IsEnabled="{Binding Path=IsEditable}"/>

<Button Template="{StaticResource buttonTemp1}"
        Command="{Binding ContactCommand}"
        CommandParameter="searchCompany"
        Content="Search"
        Width="80"
        Grid.Row="0" Grid.Column="2"
        VerticalAlignment="Top"
        Margin="0"
        HorizontalAlignment="Left"
        IsEnabled="{Binding Path=IsEditable}"/>

当您使用caliburn.micro时,是一个出色的解决方案。
matze8426 '18年

Answers:


264

让我分三个部分回答您的问题。

  1. 我想知道您的示例中的“ cs.txtCompanyID”是什么?是TextBox控件吗?如果是,则说明您的方法错误。一般来说,在ViewModel中对UI进行任何引用不是一个好主意。您可以问“为什么?” 但这是要在Stackoverflow上发布的另一个问题:)。

  2. 跟踪Focus问题的最佳方法是...调试.Net源代码。别开玩笑了 它多次节省了我很多时间。要启用.net源代码调试,请参阅Shawn Bruke的博客。

  3. 最后,我用来从ViewModel设置焦点的一般方法是附加属性。我写了非常简单的附加属性,可以在任何UIElement上进行设置。例如,它可以绑定到ViewModel的属性“ IsFocused”。这里是:

    public static class FocusExtension
    {
        public static bool GetIsFocused(DependencyObject obj)
        {
            return (bool) obj.GetValue(IsFocusedProperty);
        }
    
        public static void SetIsFocused(DependencyObject obj, bool value)
        {
            obj.SetValue(IsFocusedProperty, value);
        }
    
        public static readonly DependencyProperty IsFocusedProperty =
            DependencyProperty.RegisterAttached(
                "IsFocused", typeof (bool), typeof (FocusExtension),
                new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));
    
        private static void OnIsFocusedPropertyChanged(
            DependencyObject d, 
            DependencyPropertyChangedEventArgs e)
        {
            var uie = (UIElement) d;
            if ((bool) e.NewValue)
            {
                uie.Focus(); // Don't care about false values.
            }
        }
    }

    现在,在您的View(在XAML中)中,您可以将此属性绑定到您的ViewModel:

    <TextBox local:FocusExtension.IsFocused="{Binding IsUserNameFocused}" />

希望这可以帮助 :)。如果不是,请参考答案2。

干杯。


5
好主意。我需要将IsUserNameFocused设置为true,然后再次设置为false才能正常工作,对吗?
山姆

19
你也应该叫Keyboard.Focus(uie);从您的OnIsFocusedPropertyChanged活动,如果你希望你的控制,以接收键盘焦点和逻辑焦点
雷切尔

6
应该如何使用?如果将属性设置为true,则控件将处于焦点状态。但是,当我回到这种观点时,它将总是再次聚焦。从OnIsFocusedPropertyChanged重置它不会更改此设置。从ViewModel设置它之后直接重置它不再关注任何事情。没用 那70名支持者到底做了什么?
ygoe

2
我努力在WPF应用程序中显示的对话框中设置文本框的焦点,而WPF应用程序将该对话框显示为UserControl。在尝试了许多不同的方法之后,我终于使焦点得以发挥作用。在我将其调整为使用Dispatcher.CurrentDispatcher.BeginInvoke进行Focus调用后,上面的代码工作了:Dispatcher.CurrentDispatcher.BeginInvoke((Action)(()=> {uie.Focus(); //不在乎false值}));
2013年

4
我还更改了回调:...if ((bool)e.NewValue && uie.Dispatcher != null) { uie.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => uie.Focus())); // invoke behaves nicer, if e.g. you have some additional handler attached to 'GotFocus' of UIE. uie.SetValue(IsFocusedProperty, false); // reset bound value if possible, to allow setting again ... 有时,如果我想多次设置焦点,有时甚至必须在ViewModel中将'IsFocused'重置为false。但是随后它起作用了,其他方法失败了。
Simon D.

75

我知道这个问题到目前为止已经被回答了上千次,但是我对Anvaka的贡献进行了一些修改,我认为这将帮助其他遇到类似问题的人。

首先,我将上述附加属性更改为:

public static class FocusExtension
{
    public static readonly DependencyProperty IsFocusedProperty = 
        DependencyProperty.RegisterAttached("IsFocused", typeof(bool?), typeof(FocusExtension), new FrameworkPropertyMetadata(IsFocusedChanged){BindsTwoWayByDefault = true});

    public static bool? GetIsFocused(DependencyObject element)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }

        return (bool?)element.GetValue(IsFocusedProperty);
    }

    public static void SetIsFocused(DependencyObject element, bool? value)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }

        element.SetValue(IsFocusedProperty, value);
    }

    private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var fe = (FrameworkElement)d;

        if (e.OldValue == null)
        {
            fe.GotFocus += FrameworkElement_GotFocus;
            fe.LostFocus += FrameworkElement_LostFocus;
        }

        if (!fe.IsVisible)
        {
            fe.IsVisibleChanged += new DependencyPropertyChangedEventHandler(fe_IsVisibleChanged);
        }

        if ((bool)e.NewValue)
        {
            fe.Focus();
        }
    }

    private static void fe_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        var fe = (FrameworkElement)sender;
        if (fe.IsVisible && (bool)((FrameworkElement)sender).GetValue(IsFocusedProperty))
        {
            fe.IsVisibleChanged -= fe_IsVisibleChanged;
            fe.Focus();
        }
    }

    private static void FrameworkElement_GotFocus(object sender, RoutedEventArgs e)
    {
        ((FrameworkElement)sender).SetValue(IsFocusedProperty, true);
    }

    private static void FrameworkElement_LostFocus(object sender, RoutedEventArgs e)
    {
        ((FrameworkElement)sender).SetValue(IsFocusedProperty, false);
    }
}

我添加可见性引用的原因是标签。显然,如果您在最初可见的选项卡之外的任何其他选项卡上使用了附加属性,则直到您手动将控件聚焦后,附加属性才起作用。

另一个障碍是创建一种更优雅的方法来在失去焦点时将基础属性重置为false。那就是失去焦点事件发生的地方。

<TextBox            
    Text="{Binding Description}"
    FocusExtension.IsFocused="{Binding IsFocused}"/>

如果有更好的方法来处理可见度问题,请告诉我。

注意:感谢Apfelkuacha的建议将BindsTwoWayByDefault放在DependencyProperty中。我很早以前已经在自己的代码中做到了这一点,但是从未更新过这篇文章。由于此更改,在WPF代码中不再需要Mode = TwoWay。


9
这对我来说效果很好,除了我需要在GotFocus / LostFocus中添加“ if(e.Source == e.OriginalSource)”检查,否则在UserControl上使用时,它(从字面上看)会出现stackoverflows,这确实会将焦点重定向到内部零件。我删除了Visible检查,接受了它像.Focus()方法一样工作的事实。如果.Focus()不起作用,则绑定不起作用-这对于我的情况是可以的。
HelloSam

1
我在WF 4.5中使用它。在IsFocusedChanged上,我有一个场景(一个Activity重新加载了),其中e.NewValue为null并引发异常,因此请首先检查该异常。进行此较小的更改,一切正常。
Olaru Mircea 2015年

1
感谢此wprks太棒了:)我刚刚在'FrameworkPropertyMetadata'处添加了'{BindsTwoWayByDefault = true}'来将默认模式设置为TwoWayBinding,因此不需要每次绑定
R00st3r

1
我意识到这是一个旧答案,但是我遇到了一种情况,我要将焦点转移到的控件的IsEnabled属性绑定到多值转换器。显然,在多值转换器执行之前会调用GotFocus事件处理程序...这意味着该控件在那时已被禁用,因此,一旦GotFocus完成,就将调用LostFocus(我想是因为该控件仍处于禁用状态) 。关于如何处理的任何想法?
马克·奥尔伯特

1
@MarkOlbert使用fe.Dispatcher.BeginInvoke(new Action(() => { fe.Focus(); }), DispatcherPriority.Loaded);它在加载后进行更新。此处的更多信息:telerik.com/forums/isfocused-property#OXgFYZFOg0WZ2rxidln61Q
Apfelkuacha,

32

我认为最好的方法是保持MVVM原理清洁,因此,基本上,您必须使用MVVM Light随附的Messenger类,以及使用方法:

在您的viewmodel(exampleViewModel.cs)中:编写以下内容

 Messenger.Default.Send<string>("focus", "DoFocus");

现在在您的View.cs(不是XAML view.xaml.cs)中,在构造函数中写入以下内容

 public MyView()
        {
            InitializeComponent();

            Messenger.Default.Register<string>(this, "DoFocus", doFocus);
        }
        public void doFocus(string msg)
        {
            if (msg == "focus")
                this.txtcode.Focus();
        }

该方法非常好,并且只需较少的代码并保持MVVM标准


9
好吧,如果您想保持MVVM原则的清洁,那么您一开始就不会在代码中编写代码。我相信附加的财产方法更加清洁。它也不会在视图模型中引入很多魔术字符串。
ΕГИІИО

32
El Nino:您究竟是从哪儿得到的想法,您的视图代码中不应包含任何内容?与UI相关的任何内容都应在视图的代码隐藏中。设置UI元素的焦点应该绝对在视图的代码后面。让viewmodel确定何时发送消息;让视图找出如何处理消息。就是MV-VM的作用:分离数据模型,业务逻辑和UI的关注。
凯尔·黑尔

基于此建议,我实现了自己的ViewCommandManager来处理连接视图中的调用命令。对于这些情况,当ViewModel需要在其View中执行某些操作时,这基本上是常规Commands的另一个方向。它使用诸如数据绑定命令和WeakReferences之类的反射来避免内存泄漏。dev.unclassified.de/source/viewcommand(也在CodeProject上使用)
ygoe 2014年

我使用这种方法来打印WPF FlowDocuments。做得很好。谢谢
Gordon Slysz

我想要一个Silverlight吗?我们可以使用吗?
Bigeyes

18

这些都不是完全适合我的,但是为了他人的利益,这就是我最终根据此处已提供的一些代码编写的内容。

用法如下:

<TextBox ... h:FocusBehavior.IsFocused="True"/>

实现方式如下:

/// <summary>
/// Behavior allowing to put focus on element from the view model in a MVVM implementation.
/// </summary>
public static class FocusBehavior
{
    #region Dependency Properties
    /// <summary>
    /// <c>IsFocused</c> dependency property.
    /// </summary>
    public static readonly DependencyProperty IsFocusedProperty =
        DependencyProperty.RegisterAttached("IsFocused", typeof(bool?),
            typeof(FocusBehavior), new FrameworkPropertyMetadata(IsFocusedChanged));
    /// <summary>
    /// Gets the <c>IsFocused</c> property value.
    /// </summary>
    /// <param name="element">The element.</param>
    /// <returns>Value of the <c>IsFocused</c> property or <c>null</c> if not set.</returns>
    public static bool? GetIsFocused(DependencyObject element)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }
        return (bool?)element.GetValue(IsFocusedProperty);
    }
    /// <summary>
    /// Sets the <c>IsFocused</c> property value.
    /// </summary>
    /// <param name="element">The element.</param>
    /// <param name="value">The value.</param>
    public static void SetIsFocused(DependencyObject element, bool? value)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }
        element.SetValue(IsFocusedProperty, value);
    }
    #endregion Dependency Properties

    #region Event Handlers
    /// <summary>
    /// Determines whether the value of the dependency property <c>IsFocused</c> has change.
    /// </summary>
    /// <param name="d">The dependency object.</param>
    /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
    private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // Ensure it is a FrameworkElement instance.
        var fe = d as FrameworkElement;
        if (fe != null && e.OldValue == null && e.NewValue != null && (bool)e.NewValue)
        {
            // Attach to the Loaded event to set the focus there. If we do it here it will
            // be overridden by the view rendering the framework element.
            fe.Loaded += FrameworkElementLoaded;
        }
    }
    /// <summary>
    /// Sets the focus when the framework element is loaded and ready to receive input.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    private static void FrameworkElementLoaded(object sender, RoutedEventArgs e)
    {
        // Ensure it is a FrameworkElement instance.
        var fe = sender as FrameworkElement;
        if (fe != null)
        {
            // Remove the event handler registration.
            fe.Loaded -= FrameworkElementLoaded;
            // Set the focus to the given framework element.
            fe.Focus();
            // Determine if it is a text box like element.
            var tb = fe as TextBoxBase;
            if (tb != null)
            {
                // Select all text to be ready for replacement.
                tb.SelectAll();
            }
        }
    }
    #endregion Event Handlers
}

11

这是一个旧线程,但是似乎没有代码的答案来解决Anavanka接受的答案的问题:如果将viewmodel中的属性设置为false,或者将属性设置为false,则该代码不起作用如果为true,则用户手动单击其他内容,然后再次将其设置为true。在这些情况下,我也无法获得Zamotic的解决方案来可靠地工作。

综合上面的一些讨论,可以为我提供以下代码,这些代码确实解决了我认为的这些问题:

public static class FocusExtension
{
    public static bool GetIsFocused(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsFocusedProperty);
    }

    public static void SetIsFocused(DependencyObject obj, bool value)
    {
        obj.SetValue(IsFocusedProperty, value);
    }

    public static readonly DependencyProperty IsFocusedProperty =
        DependencyProperty.RegisterAttached(
         "IsFocused", typeof(bool), typeof(FocusExtension),
         new UIPropertyMetadata(false, null, OnCoerceValue));

    private static object OnCoerceValue(DependencyObject d, object baseValue)
    {
        if ((bool)baseValue)
            ((UIElement)d).Focus();
        else if (((UIElement) d).IsFocused)
            Keyboard.ClearFocus();
        return ((bool)baseValue);
    }
}

话虽这么说,对于可以在代码隐藏中一行完成的事情来说,这仍然很复杂,而且CoerceValue并不是真的要以这种方式使用,所以代码隐藏可能是要走的路。


1
这始终如一地工作,而接受的答案却行不通。谢谢!
NathanAldenSr 2016年

4

就我而言,在我更改方法OnIsFocusedPropertyChanged之前,FocusExtension不起作用。原始的仅在断点停止进程时才在调试中工作。在运行时,该过程太快,没有任何反应。稍加修改,并在我们的朋友Task的帮助下,这在两种情况下都可以正常工作。

private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
  var uie = (UIElement)d;
  if ((bool)e.NewValue)
  {
    var action = new Action(() => uie.Dispatcher.BeginInvoke((Action)(() => uie.Focus())));
    Task.Factory.StartNew(action);
  }
}

3

问题在于,一旦将IsUserNameFocused设置为true,就永远不会为false。这通过处理FrameworkElement的GotFocus和LostFocus来解决。

我在源代码格式方面遇到麻烦,因此这是一个链接


1
我更改了“对象fe =(FrameworkElement)d;” 改为“ FrameworkElement fe =(FrameworkElement)d;” 所以智能感知工作

仍然不能解决问题。每当我回到该元素时,该元素都会保持专注。
ygoe

3

Anvakas出色的代码适用于Windows桌面应用程序。如果您和我一样,并且对于Windows Store应用程序需要相同的解决方案,则此代码可能很方便:

public static class FocusExtension
{
    public static bool GetIsFocused(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsFocusedProperty);
    }


    public static void SetIsFocused(DependencyObject obj, bool value)
    {
        obj.SetValue(IsFocusedProperty, value);
    }


    public static readonly DependencyProperty IsFocusedProperty =
        DependencyProperty.RegisterAttached(
         "IsFocused", typeof(bool), typeof(FocusExtension),
         new PropertyMetadata(false, OnIsFocusedPropertyChanged));


    private static void OnIsFocusedPropertyChanged(DependencyObject d,
        DependencyPropertyChangedEventArgs e)
    {
        if ((bool)e.NewValue)
        {
            var uie = d as Windows.UI.Xaml.Controls.Control;

            if( uie != null )
            {
                uie.Focus(FocusState.Programmatic);
            }
        }
    }
}

1

对于那些尝试使用上面的Anvaka解决方案的人,我遇到的问题是绑定仅在第一次工作时有效,因为lostfocus不会将该属性更新为false。您可以每次将属性手动设置为false,然后再设置为true,但是更好的解决方案是在属性中执行以下操作:

bool _isFocused = false;
    public bool IsFocused 
    {
        get { return _isFocused ; }
        set
        {
            _isFocused = false;
            _isFocused = value;
            base.OnPropertyChanged("IsFocused ");
        }
    }

这样,您只需要将其设置为true,就可以获取焦点。


为什么要有if语句?_isFocused一旦设置为false,将仅在下一行更改为value。
Damien McGivern

1
@Tyrsius您可以通过获取依赖项属性强迫圆这个问题,看看这里- social.msdn.microsoft.com/Forums/en-US/wpf/thread/...
RichardOD

1

我使用WPF / Caliburn Micro,发现“ dfaivre”已在此处提出了通用且可行的解决方案:http ://caliburnmicro.codeplex.com/discussions/222892


1

我已经按照下面的方法通过编辑代码找到了解决方案。无需先将Binding属性设置为False,然后再设置True。

public static class FocusExtension
{

    public static bool GetIsFocused(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsFocusedProperty);
    }


    public static void SetIsFocused(DependencyObject obj, bool value)
    {
        obj.SetValue(IsFocusedProperty, value);
    }


    public static readonly DependencyProperty IsFocusedProperty =
        DependencyProperty.RegisterAttached(
         "IsFocused", typeof(bool), typeof(FocusExtension),
         new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));


    private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d != null && d is Control)
        {
            var _Control = d as Control;
            if ((bool)e.NewValue)
            {
                // To set false value to get focus on control. if we don't set value to False then we have to set all binding
                //property to first False then True to set focus on control.
                OnLostFocus(_Control, null);
                _Control.Focus(); // Don't care about false values.
            }
        }
    }

    private static void OnLostFocus(object sender, RoutedEventArgs e)
    {
        if (sender != null && sender is Control)
        {
            (sender as Control).SetValue(IsFocusedProperty, false);
        }
    }
}

0

对于Silverlight:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace MyProject.Behaviors
{
    public class FocusBehavior : Behavior<Control>
    {
        protected override void OnAttached()
        {
            this.AssociatedObject.Loaded += AssociatedObject_Loaded;
            base.OnAttached();
        }

        private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            this.AssociatedObject.Loaded -= AssociatedObject_Loaded;
            if (this.HasInitialFocus || this.IsFocused)
            {
                this.GotFocus();
            }
        }

        private void GotFocus()
        {
            this.AssociatedObject.Focus();
            if (this.IsSelectAll)
            {
                if (this.AssociatedObject is TextBox)
                {
                    (this.AssociatedObject as TextBox).SelectAll();
                }
                else if (this.AssociatedObject is PasswordBox)
                {
                    (this.AssociatedObject as PasswordBox).SelectAll();
                }
                else if (this.AssociatedObject is RichTextBox)
                {
                    (this.AssociatedObject as RichTextBox).SelectAll();
                }
            }
        }

        public static readonly DependencyProperty IsFocusedProperty =
            DependencyProperty.Register(
                "IsFocused",
                typeof(bool),
                typeof(FocusBehavior),
                new PropertyMetadata(false, 
                    (d, e) => 
                    {
                        if ((bool)e.NewValue)
                        {
                            ((FocusBehavior)d).GotFocus();
                        }
                    }));

        public bool IsFocused
        {
            get { return (bool)GetValue(IsFocusedProperty); }
            set { SetValue(IsFocusedProperty, value); }
        }

        public static readonly DependencyProperty HasInitialFocusProperty =
            DependencyProperty.Register(
                "HasInitialFocus",
                typeof(bool),
                typeof(FocusBehavior),
                new PropertyMetadata(false, null));

        public bool HasInitialFocus
        {
            get { return (bool)GetValue(HasInitialFocusProperty); }
            set { SetValue(HasInitialFocusProperty, value); }
        }

        public static readonly DependencyProperty IsSelectAllProperty =
            DependencyProperty.Register(
                "IsSelectAll",
                typeof(bool),
                typeof(FocusBehavior),
                new PropertyMetadata(false, null));

        public bool IsSelectAll
        {
            get { return (bool)GetValue(IsSelectAllProperty); }
            set { SetValue(IsSelectAllProperty, value); }
        }

    }
}

LoginViewModel.cs:

    public class LoginModel : ViewModelBase
    {
        ....

        private bool _EmailFocus = false;
        public bool EmailFocus
        {
            get
            {
                return _EmailFocus;
            }
            set
            {
                if (value)
                {
                    _EmailFocus = false;
                    RaisePropertyChanged("EmailFocus");
                }
                _EmailFocus = value;
                RaisePropertyChanged("EmailFocus");
            }
        }
       ...
   }

Login.xaml:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:beh="clr-namespace:MyProject.Behaviors"

<TextBox Text="{Binding Email, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <i:Interaction.Behaviors>
        <beh:FocusBehavior IsFocused="{Binding EmailFocus}" IsSelectAll="True"/>
    </i:Interaction.Behaviors>
</TextBox>

要么

<TextBox Text="{Binding Email, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <i:Interaction.Behaviors>
        <beh:FocusBehavior HasInitialFocus="True" IsSelectAll="True"/>
    </i:Interaction.Behaviors>
</TextBox>

要设置焦点,只需在代码中执行即可:

EmailFocus = true;

请记住,此插件是html页面的一部分,因此页面中的其他控件可能具有焦点

if (!Application.Current.IsRunningOutOfBrowser)
{
    System.Windows.Browser.HtmlPage.Plugin.Focus();
}

0

您可以使用ViewCommand设计模式。它描述了MVVM设计模式通过命令从ViewModel控制View的方法。

我已经根据King A.Majid的使用MVVM Light Messenger类的建议实现了它。ViewCommandManager类处理已连接视图中的调用命令。从本质上讲,这是常规命令的另一个方向,在这种情况下,当ViewModel需要在其View中执行某些操作时。它使用诸如数据绑定命令和WeakReferences之类的反射来避免内存泄漏。

http://dev.unclassified.de/source/viewcommand(也发布在CodeProject上)


0

似乎没有人包括最后一步,可以很容易地通过绑定变量更新属性。这是我想出的。让我知道是否有更好的方法可以做到这一点。

XAML

    <TextBox x:Name="txtLabel"
      Text="{Binding Label}"
      local:FocusExtension.IsFocused="{Binding txtLabel_IsFocused, Mode=TwoWay}" 
     />

    <Button x:Name="butEdit" Content="Edit"
        Height="40"  
        IsEnabled="{Binding butEdit_IsEnabled}"                        
        Command="{Binding cmdCapsuleEdit.Command}"                            
     />   

视图模型

    public class LoginModel : ViewModelBase
    {

    public string txtLabel_IsFocused { get; set; }                 
    public string butEdit_IsEnabled { get; set; }                


    public void SetProperty(string PropertyName, string value)
    {
        System.Reflection.PropertyInfo propertyInfo = this.GetType().GetProperty(PropertyName);
        propertyInfo.SetValue(this, Convert.ChangeType(value, propertyInfo.PropertyType), null);
        OnPropertyChanged(PropertyName);
    }                


    private void Example_function(){

        SetProperty("butEdit_IsEnabled", "False");
        SetProperty("txtLabel_IsFocused", "True");        
    }

    }

0

首先,我要感谢Avanka帮助我解决了焦点问题。但是,他发布的代码中存在一个错误,即该行中的内容:if(e.OldValue == null)

我遇到的问题是,如果您首先单击视图并聚焦控件,则e.oldValue不再为null。然后,当您将变量设置为第一次使控件聚焦时,这将导致没有设置lostfocus和getfocus处理程序。我对此的解决方案如下:

public static class ExtensionFocus
    {
    static ExtensionFocus()
        {
        BoundElements = new List<string>();
        }

    public static readonly DependencyProperty IsFocusedProperty =
        DependencyProperty.RegisterAttached("IsFocused", typeof(bool?),
        typeof(ExtensionFocus), new FrameworkPropertyMetadata(false, IsFocusedChanged));

    private static List<string> BoundElements;

    public static bool? GetIsFocused(DependencyObject element)
        {
        if (element == null)
            {
            throw new ArgumentNullException("ExtensionFocus GetIsFocused called with null element");
            }
        return (bool?)element.GetValue(IsFocusedProperty);
        }

    public static void SetIsFocused(DependencyObject element, bool? value)
        {
        if (element == null)
            {
            throw new ArgumentNullException("ExtensionFocus SetIsFocused called with null element");
            }
        element.SetValue(IsFocusedProperty, value);
        }

    private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
        var fe = (FrameworkElement)d;

        // OLD LINE:
        // if (e.OldValue == null)
        // TWO NEW LINES:
        if (BoundElements.Contains(fe.Name) == false)
            {
            BoundElements.Add(fe.Name);
            fe.LostFocus += OnLostFocus;
            fe.GotFocus += OnGotFocus;
            }           


        if (!fe.IsVisible)
            {
            fe.IsVisibleChanged += new DependencyPropertyChangedEventHandler(fe_IsVisibleChanged);
            }

        if ((bool)e.NewValue)
            {
            fe.Focus();             
            }
        }

    private static void fe_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
        var fe = (FrameworkElement)sender;

        if (fe.IsVisible && (bool)((FrameworkElement)sender).GetValue(IsFocusedProperty))
            {
            fe.IsVisibleChanged -= fe_IsVisibleChanged;
            fe.Focus();
            }
        }

    private static void OnLostFocus(object sender, RoutedEventArgs e)
        {
        if (sender != null && sender is Control s)
            {
            s.SetValue(IsFocusedProperty, false);
            }
        }

    private static void OnGotFocus(object sender, RoutedEventArgs e)
        {
        if (sender != null && sender is Control s)
            {
            s.SetValue(IsFocusedProperty, true);
            }
        }
    }

0

只是这样做:

<Window x:class...
   ...
   ...
   FocusManager.FocusedElement="{Binding ElementName=myTextBox}"
>
<Grid>
<TextBox Name="myTextBox"/>
...

我喜欢这个。如果要设置初始焦点,此方法效果很好。
user2430797

0

在实现了可接受的答案之后,我确实遇到了一个问题,即在使用Prism导航视图时,TextBox仍不会获得焦点。对PropertyChanged处理程序的微小更改解决了它

    private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var uie = (UIElement)d;
        if ((bool)e.NewValue)
        {
            uie.Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
            {
                uie.Focus();
            }));
        }
    }

0

基于@Sheridan另一种方法回答这里

 <TextBox Text="{Binding SomeText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
        <TextBox.Style>
            <Style>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding SomeTextIsFocused, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Value="True">
                        <Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>

在视图模型中,以通常的方式设置绑定,然后将SomeTextIsFocused设置为true以将焦点设置在文本框上


-1

我发现Crucial解决IsVisible问题的方法非常有用。它并不能完全解决我的问题,但是遵循IsEnabled模式相同模式的一些额外代码确实可以解决。

我向IsFocusedChanged方法添加了:

    if (!fe.IsEnabled)
    {
        fe.IsEnabledChanged += fe_IsEnabledChanged;
    }

这是处理程序:

private static void fe_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    var fe = (FrameworkElement)sender;
    if (fe.IsEnabled && (bool)((FrameworkElement)sender).GetValue(IsFocusedProperty))
    {
        fe.IsEnabledChanged -= fe_IsEnabledChanged;
        fe.Focus();
    }
}

-1
public class DummyViewModel : ViewModelBase
    {
        private bool isfocused= false;
        public bool IsFocused
        {
            get
            {
                return isfocused;
            }
            set
            {
                isfocused= value;
                OnPropertyChanged("IsFocused");
            }
        }
    }

-7
System.Windows.Forms.Application.DoEvents();
Keyboard.Focus(tbxLastName);

1
OP正在使用WPF。WinForms的焦点代码将无济于事。
乔什·G
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.