问题
I am using MVVM. I have a DataGrid which lists some airports. Now I have a textbox let the user to input some keywords to search for a particular airport so that the airport list will only display matched airports.
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");
}
}
view:
<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>
The problem is that the value of "Airport" will not be transmitted from UI to Property unless the focus is removed from the textbox, hence it leads to a null value exception in the command. I think to use a button for search instead of using "TextChanged" event could solve this but not user-friendly enough. How can I keep the "TextChanged" way and solve this using MVVM? Thanks.
回答1:
Default mode of updating source for TextBox.Text property is LostFocus
. Change it to PropertyChanged
.
Text="{Binding Airport, UpdateSourceTrigger=PropertyChanged}"
And if you are working with .net 4.5 or newer, I suggest to use binding Delay
as well. With Delay Airport
property will be updated after user stopped typing, not on every key press. Search in this case can be triggered from Airport
setter, which should allow user to type full search keyword, before actually searching it
Text="{Binding Airport, Delay=400, UpdateSourceTrigger=PropertyChanged}"
来源:https://stackoverflow.com/questions/51722545/binding-from-ui-to-view-model-property-requires-focus-to-be-removed-from-the-tex