我有combobox
绑定到以下列表:
private List<string> strList;
public List<string> StrList
{
get { return strList; }
set
{
strList = value;
OnPropertyChanged("StrList");
}
}
所选项目将绑定到下一个对象:
private string str;
public string Str
{
get { return str; }
set
{
if (str != value)
{
str = value;
OnPropertyChanged("Str");
}
}
}
关注组合框:
<ComboBox ItemsSource="{Binding StrList}"
SelectedItem="{Binding Str,UpdateSourceTrigger=LostFocus}"
Height="50" Width="200"/>
我希望绑定仅在丢失焦点时发生,并且在使用键盘键更改值时。
因此UpdateSourceTrigger=LostFocus
。
我的问题是如何通过更改键盘上的值来实现绑定?
答案 0 :(得分:0)
我创建了一个行为,在按下键的情况下我更新了绑定:
public class KeysChangedBehavior : Behavior<ComboBox>
{
protected override void OnAttached()
{
this.AssociatedObject.AddHandler(ComboBox.KeyDownEvent,
new RoutedEventHandler(this.OnKeysChanged));
this.AssociatedObject.AddHandler(ComboBox.KeyUpEvent,
new RoutedEventHandler(this.OnKeysChanged));
}
protected void OnKeysChanged(object sender, RoutedEventArgs e)
{
BindingExpression _binding = ((ComboBox)sender).GetBindingExpression(ComboBox.SelectedItemProperty);
if (_binding != null)
_binding.UpdateSource();
}
}
这里是组合框:
<ComboBox ItemsSource="{Binding StrList}" SelectedItem="{Binding Str,UpdateSourceTrigger=LostFocus}" Height="50" Width="200">
<i:Interaction.Behaviors>
<KeysChangedBehavior/>
</i:Interaction.Behaviors>
</ComboBox>