4

I want to stop the ComboBox_SelectionChanged event from being fired at the UI loading. It should happen only when the user makes some change in the combo box.

To do this, I have written the following in .xam.cs file.

  private void myComboBox_SelectionChanged(object sender,   SelectionChangedEventArgs e)
      {
        ComboBox cb = (ComboBox)sender;
        if (!cb.IsFocused)
        {
            return;
        }
        else
           ViewModel.OnPropertyChanged("MyProperty");
     }

But this does not even fire the event when the user makes the change. Where have I gone wrong ?

I know there is a similar question in stackoverflow. But the solutions in it did not work for me. pls help.

nidarshani fernando
  • 493
  • 4
  • 10
  • 26

2 Answers2

2

found the solution. we just need to combine the Selection_Changed event with PreviewMouseDown event.

could the SelectionChanged event in WPF be handled only for user interaction?

Community
  • 1
  • 1
nidarshani fernando
  • 493
  • 4
  • 10
  • 26
0

This is an example XAML:

<av:ComboBox x:Name="cmbChargeUnit" HorizontalAlignment="Left" Margin="548,15,0,0" Width="187" ItemsSource="{av:Binding ChargeUnits}" DisplayMemberPath="ChargeUnitDescription" SelectedValue="{Binding SelectedChargeUnit}" VerticalAlignment="Top" Background="#FFCBCBCB" Height="20" IsSynchronizedWithCurrentItem="True"  SelectedIndex="0"  BorderBrush="#FF7070CB"/>

VM:

public ChargeUnit SelectedChargeUnit
    {
        get { return _selectedChargeUnit; }
        set
        {
            _selectedChargeUnit = value;
            OnPropertyChanged("SelectedChargeUnit");
            if (SelectedAttributeId != null)//Only Load when an attribute is entered
            {
                LoadRates();
            }
        }
    }
David B
  • 889
  • 2
  • 11
  • 29
  • How can it ever become null ? I have a property like that. But it's always set to some value. It only gets changed when the user changes the items in the combo box – nidarshani fernando May 12 '15 at 09:31
  • That part is to check for another property on my ViewModel before calling a method to load rates that use that Property, like I said it is just an example, when you select your item in your combobox it will hit the Set accessor, then you can call a method which will be called everytime this value changes. – David B May 12 '15 at 09:33
  • I have already tried that too. That too does the same. Fires the combobox selection changed event at the page loading – nidarshani fernando May 12 '15 at 09:37
  • It should not fire an event, as there should not be an event? Just a property? The property should hit its Set accessor when selecting an Item in the combo. It will hit its Get accessor when the window loads. – David B May 12 '15 at 09:50