如何使用MVVM Pattern以编程方式更改wpf中的焦点文本框?

时间:2014-12-18 08:54:56

标签: c# wpf mvvm

我有像这样的

聚焦元素messagetextbox
<DockPanel FocusManager.FocusedElement="{Binding ElementName=TextBox1}">    
    <TextBox Name="TextBox1" Text="{Binding Message}"/>
    <TextBox Name="TextBox2" Text="{Binding Message}"/>
    <TextBox Name="TextBox3" Text="{Binding Message}"/>
</DockPanel>

但后来我想使用代码动态地使用elementname更改焦点到“TextBox2”。那怎么做呢。假设我有像这样的View Model

private string elementToFocus;
public string ElementToFocus
{
  set{
    this.elementToFocus=value;
    OnPropertyChanged("ElementToFocus");
  }
  get{
    return this.elementToFocus;
  }
}

Anda我想要这种代码,但我怎么做呢?

<DockPanel FocusManager.FocusedElement="{Binding ElementName={Binding ElementToFocus}}">   

因为我有很多控制权,有时会以编程方式移动焦点。感谢

1 个答案:

答案 0 :(得分:0)

由于设置Focus是View相关的东西,我个人更喜欢使用Messager类(由GalaSoft-Mvvmlight提供),以及如何:

1.register you查看以从ViewModel接收消息并设置这些消息的处理程序(在View的构造函数内):

Messenger.Default.Register<NotificationMessage>(this, (message) =>
        {
            switch (message.Notification)
            {
                case "TextBox1":
                   TextBox1.Focus();
                    break;
               case "TextBox2":
                   TextBox2.Focus();
                    break;
                case "TextBox3":
                   TextBox3.Focus();
                    break;
            }
        });

2.当您想要更改焦点时,只需从包含控件名称的VM发送一条消息,将焦点设置为:

Messenger.Default.Send(new NotificationMessage("TextBox1"))
相关问题