Binding from UI to view model property requires focus to be removed from the TextBox

孤人 提交于 2021-01-29 12:50:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!