绑定不是在的CommandBinding
问题描述:
执行我有这样的XAML代码:绑定不是在的CommandBinding
<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>
搜索,方法是这样的:
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();
}
但是,如果我按进入而焦点在文本框中时,绑定不是computet,LastName是空值。是什么原因?我怎样才能避免这种情况?或者是否可以显式调用绑定操作?
预先感谢您。
答
设置UpdateSourceTrigger
属性PropertyChanged
:
<TextBox Text="{Binding LastName, UpdateSourceTrigger=PropertyChanged}">
这将导致源属性(LastName
)立即设置:https://msdn.microsoft.com/en-us/library/system.windows.data.updatesourcetrigger(v=vs.110).aspx
答
,我可以看到你的Window
是一个视图模型为它。我建议你使用MVVM并设有独立的类,你可以把所需的ICommand
视图模型,并使用CommandParameter
上KeyBinding
:
<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>