[英]How to programmatically change focus textbox in wpf using MVVM Pattern?
I have focused element messagetextbox like this 我已经像这样集中了元素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>
But later I want to change focus dynamically using elementname to "TextBox2" using code. 但是稍后我想使用代码将elementname动态更改为“ TextBox2”。 So how to do this. 那么如何做到这一点。 Suppose I have View Model like this 假设我有这样的视图模型
private string elementToFocus;
public string ElementToFocus
{
set{
this.elementToFocus=value;
OnPropertyChanged("ElementToFocus");
}
get{
return this.elementToFocus;
}
}
Anda I want maybe this kind of code but How I can do this? 安达,我想要这种代码,但是我该怎么做呢?
<DockPanel FocusManager.FocusedElement="{Binding ElementName={Binding ElementToFocus}}">
Because I have so many control and sometimes move focus programmatically. 因为我有很多控制权,有时会以编程方式移动焦点。 Thanks 谢谢
Since setting the Focus is a View related thing, I personally prefer doing it using the Messager Class (Provided by GalaSoft-Mvvmlight), and here how: 由于设置Focus是与View相关的事情,因此我个人更喜欢使用Messager类(由GalaSoft-Mvvmlight提供)进行此操作,并在此处进行操作:
1.register you View to receive messages from ViewModels and set the handler for those messages (inside the Constructor of the View): 1.注册您的视图以接收来自ViewModels的消息并为这些消息设置处理程序(在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.When you want to change the focus just send a message from your VM containing the Name of the Control to set the focus to : 2.要更改焦点时,只需从VM发送一条消息,其中包含控件名称即可将焦点设置为:
Messenger.Default.Send(new NotificationMessage("TextBox1"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.