我在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>
在viewmodel中我创建了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”。但这不会发生。
什么可能导致这个问题?