Search code examples
c#wpfbindingcomboboxupdatesourcetrigger

Binding happened also by changing the values from the keyboard


I have a combobox that is bind to the following list:

    private List<string> strList;
    public List<string> StrList
    {
        get { return strList; }
        set
        {
            strList = value;
            OnPropertyChanged("StrList");
        }
    }

The selected item is bind to the next object:

    private string str;
    public string Str
    {
        get { return str; }
        set
        {
            if (str != value)
            {
                str = value;
                OnPropertyChanged("Str");
            }
        }
    }

Following the combobox:

<ComboBox ItemsSource="{Binding StrList}"
          SelectedItem="{Binding Str,UpdateSourceTrigger=LostFocus}"
          Height="50" Width="200"/>

I want that the binding happens only on lost focus, and when changing the values ​​with the keys of the keyboard. Therefore UpdateSourceTrigger=LostFocus.

My question is how to do that binding happened also by changing the values ​​from the keyboard?


Solution

  • I created a behavior and in it I renewed the binding in a case of pressing the keys:

     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();
            }
        }
    

    Here the combobox:

        <ComboBox ItemsSource="{Binding StrList}" SelectedItem="{Binding Str,UpdateSourceTrigger=LostFocus}" Height="50" Width="200">
            <i:Interaction.Behaviors>
                <KeysChangedBehavior/>
            </i:Interaction.Behaviors>
        </ComboBox>