0

我有一个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

我的问题是如何通过更改键盘的值来进行绑定?

4

1 回答 1

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>
于 2013-08-15T09:17:05.467 回答