Wpf 从UI绑定到视图模型属性需要从文本框中删除焦点
我正在使用MVVM。我有一个列出一些机场的数据网格。现在我有了一个文本框,用户可以输入一些关键字来搜索特定的机场,这样机场列表将只显示匹配的机场Wpf 从UI绑定到视图模型属性需要从文本框中删除焦点,wpf,xaml,mvvm,data-binding,Wpf,Xaml,Mvvm,Data Binding,我正在使用MVVM。我有一个列出一些机场的数据网格。现在我有了一个文本框,用户可以输入一些关键字来搜索特定的机场,这样机场列表将只显示匹配的机场 private string airport; public string Airport { get { return airport; } //the following will not be executed unless the cursor is removed from the textbox set {
private string airport;
public string Airport
{
get { return airport; }
//the following will not be executed unless the cursor is removed from the textbox
set
{
airport = value;
//OnPropertyChanged("Airport");
}
}
视图:
问题是,“Airport”的值不会从UI传输到属性,除非焦点从文本框中移除,因此它会导致命令中出现空值异常。我认为使用一个按钮来搜索而不是使用“TextChanged”事件可以解决这个问题,但不够友好。我如何保持“TextChanged”的方式并使用MVVM解决这个问题?谢谢 更新文本框源的默认模式。文本属性为
LostFocus
。将其更改为PropertyChanged
Text=“{Binding Airport,UpdateSourceTrigger=PropertyChanged}”
如果您使用的是.NET4.5或更高版本,我建议您也使用绑定Delay
。延迟Airport
属性将在用户停止键入后更新,而不是在每次按键时更新。在这种情况下,可以从Airport
setter触发搜索,这应该允许用户在实际搜索之前键入完整的搜索关键字
Text=“{Binding Airport,Delay=400,UpdateSourceTrigger=PropertyChanged}”
文本框更新源的默认模式。Text属性为LostFocus
。将其更改为PropertyChanged
Text=“{Binding Airport,UpdateSourceTrigger=PropertyChanged}”
如果您使用的是.NET4.5或更高版本,我建议您也使用绑定Delay
。延迟Airport
属性将在用户停止键入后更新,而不是在每次按键时更新。在这种情况下,可以从Airport
setter触发搜索,这应该允许用户在实际搜索之前键入完整的搜索关键字
Text=“{Binding Airport,Delay=400,UpdateSourceTrigger=PropertyChanged}”
<TextBox x:Name="textBox_Airport" Text="{Binding Airport}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction Command="{Binding Command_Airport}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>