WPF - How to report what caused the ComboBox_SelectionChanged event

Is there a way to tell how the ComboBox_SelectionChanged event was created in WPF.

That is, was the event raised as a result of user interaction or as a result of a change in the property to which it is bound?

+3
source share
3 answers

In the ComboBox.SelectionChanged event, the sender is always a ComboBox, and there will be nothing in SelectionChangedEventArgs that helps you.

. , , , System.Windows.Controls.Primitives.Selector.OnSelectedItemsCollectionChanged(, NotifyCollectionChangedArgs). , . .

, . , - .

1. , , "" "":

public EventingConverter : IValueConverter
{
  public event EventHandler Converted;
  public event EventHandler ConvertedBack;

  public object Convert(object value, ...)
  {
    if(Converted!=null) Converted(this, EventArgs.Empty);
    return value;
  }
  public object ConvertBack(object value, ...)
  {
    if(ConvertedBack!=null) ConvertedBack(this, EventArgs.Empty);
    return value;
  }
}

2. ( , )

<ComboBox ...>
  <ComboBox.SelectedValue>
    <Binding Path="..." ...>
      <Binding.Converter>
        <local:EventingConverter
          Converted="ComboBoxSelectedValue_Converted"
          ConvertedBack="ComboBoxSelectedValue_ConvertedBack" />
      </Binding.Converter>
    </Binding>
  </ComboBox.SelectedValue>
</ComboBox>

ComboBoxSelectedValue_Converted ComboBoxSelectedValue_ConvertedBack .

. , .

XAML,

XAML, (, ), . , ( ), MultiBindings ( ).

, , , , .

, , , - " ComboBox". , , . , , " " " " " 5".

+4

: . , , , . , , , DropDownOpened/Closed KeyDown/Up, Stylus *.

+2

I also met this problem and solved it using a boolean variable bInternalChange.

Imagine an interface that converts ° C to ° F and vice versa with two ComboBoxes. When you select a value in the first, the selection of the second is updated, and the choice of the value in the second is updated first. It creates an endless loop if you do not distinguish user interface changes from internal changes.

bool bInternalChange = false;
private void ComboBoxF_SelectionChanged(...)
{
    if (!bInternalChange)
    {
        bInternalChange = true;
        ComboBoxC.SelectedValue = ConvertFtoC(...);
        bInternalChange = false;
    }
}
private void ComboBoxC_SelectionChanged(...)
{
    if (!bInternalChange)
    {
        bInternalChange = true;
        ComboBoxF.SelectedValue = ConvertCtoF(...);
        bInternalChange = false;
    }
}
+1
source

Source: https://habr.com/ru/post/1722163/


All Articles