【发布时间】:2016-08-13 12:11:47
【问题描述】:
我在 MVVM 中有一个带有 2 个文本框的 WPF 应用程序,我想动态设置焦点
在 WPF 中,我为文本框“NodeBarcode_1”和“NodeBarcode_2”创建了 2 个数据触发器
<DataTrigger Binding="{Binding NodeBarcode_1_GetFocusNow}" Value="True">
<Setter Property="FocusManager.FocusedElement" Value ="{Binding ElementName=NodeBarcode_1}"/>
</DataTrigger>
<DataTrigger Binding="{Binding NodeBarcode_2_GetFocusNow}" Value="True">
<Setter Property="FocusManager.FocusedElement" Value ="{Binding ElementName=NodeBarcode_2}"/>
</DataTrigger>
在视图模型中,我创建了 2 个布尔变量:
public const string NodeBarcode_1_GetFocusNowPropertyName = "NodeBarcode_1_GetFocusNow";
private bool _NodeBarcode_1_GetFocusNow = false;
public bool NodeBarcode_1_GetFocusNow
{
get
{
return _NodeBarcode_1_GetFocusNow;
}
set
{
if (_NodeBarcode_1_GetFocusNow == value)
{
return;
}
_NodeBarcode_1_GetFocusNow = value;
RaisePropertyChanged(NodeBarcode_1_GetFocusNowPropertyName);
}
}
public const string NodeBarcode_2_GetFocusNowPropertyName = "NodeBarcode_2_GetFocusNow";
private bool _NodeBarcode_2_GetFocusNow = false;
public bool NodeBarcode_2_GetFocusNow
{
get
{
return _NodeBarcode_2_GetFocusNow;
}
set
{
if (_NodeBarcode_2_GetFocusNow == value)
{
return;
}
_NodeBarcode_2_GetFocusNow = value;
RaisePropertyChanged(NodeBarcode_2_GetFocusNowPropertyName);
}
}
我创建了 2 个在用户在文本框中输入条形码时执行的方法
private void NodeBarcode_1_Execute(EventArgs e)
{
try
{
IProduct NodeObj = ObjectFactory<IProduct>.Create("Node");
NodeObj.Barcode = NodeBarcode_1_txt;
NodeObj.Validation();
labelAppObj.AddProduct(NodeObj);
NodeBarcode_2_GetFocusNow = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
NodeBarcode_1_txt = string.Empty;
}
}
private void NodeBarcode_2_Execute(EventArgs e)
{
try
{
IProduct NodeObj = ObjectFactory<IProduct>.Create("Node");
NodeObj.Barcode = NodeBarcode_2_txt;
NodeObj.Validation();
labelAppObj.AddProduct(NodeObj);
NodeBarcode_1_GetFocusNow = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
NodeBarcode_2_txt = string.Empty;
}
}
当用户扫描文本框“NodeBarcode_1”中的第一个条形码时,焦点转到“NodeBarcode_2”。没问题。但是当用户扫描“NodeBarcode_2”中的下一个条形码时,我希望焦点回到“NodeBarcode_1”。但这不会发生。
什么会导致这个问题?
【问题讨论】: