【问题标题】:Binding happened also by changing the values from the keyboard通过更改键盘上的值也发生了绑定
【发布时间】:2013-08-15 07:16:40
【问题描述】:

我有一个绑定到以下列表的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

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

【问题讨论】:

  • 您似乎是在说您希望绑定在 ComboBox 失去焦点时起作用,而且在您更改值时...尝试设置 UpdateSourceTrigger=PropertyChanged 吗?

标签: c# wpf binding combobox updatesourcetrigger


【解决方案1】:

我创建了一个行为,并在其中更新了按键情况下的绑定:

 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 2018-11-28
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多