我有这个xaml代码:
<Window.CommandBindings>
<CommandBinding Command="WpfApplication1:MainCommands.Search" Executed="Search"/>
</Window.CommandBindings><Grid>
<StackPanel>
<ListView ItemsSource="{Binding SearchContext}" />
<TextBox Text="{Binding LastName}">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{x:Static WpfApplication1:MainCommands.Search}" />
</TextBox.InputBindings>
</TextBox>
</StackPanel>Search-Method看起来像这样:
private void Search(object sender, RoutedEventArgs e)
{
SearchContext = new ObservableCollection<string>(list.Where(element => element.Name == LastName).Select(el => el.Name).ToList());
}MainCommands:
public static class MainCommands
{
public static RoutedCommand Search = new RoutedCommand();
}但是当焦点在textbox中时,如果我按enter,绑定是‘nt computet,LastName是Null。原因何在?我怎样才能避免这种情况?或者可以显式调用绑定操作?
提前谢谢你。
发布于 2017-08-08 17:44:05
将UpdateSourceTrigger属性设置为PropertyChanged
<TextBox Text="{Binding LastName, UpdateSourceTrigger=PropertyChanged}">这将导致立即设置源属性(LastName):https://msdn.microsoft.com/en-us/library/system.windows.data.updatesourcetrigger(v=vs.110).aspx
发布于 2017-08-08 18:39:10
正如我所看到的,您的Window是它的视图模型。我建议您使用MVVM,并为视图模型提供单独的类,以便在KeyBinding上放置所需的ICommand和使用CommandParameter
<TextBox x:Name="searchBox"
Text="{Binding LastName}">
<TextBox.InputBindings>
<KeyBinding Key="Enter"
Command="{Binding Path=SearchCommand}"
CommandParameter="{Binding Path=Text, ElementName=searchBox}" />
</TextBox.InputBindings>
</TextBox>https://stackoverflow.com/questions/45564703
复制相似问题