Nollaig
Nollaig

Reputation: 1097

WPF CollectionView.CurrentChanged event firing on load

I have a WPF app where is am setting up some comboboxes in the ViewModel constructor. I populate the comboboxes and then setup the CurrentChanged EventHandler but each time the view loads this event gets fired. I would like to be able to stop the CurrentChanged event being fired on load.

Here is my ViewModel constructor.

public MyViewModel()
    { 
        this.Initialize();
        carNames = new CollectionView(GetCarNames());//method that returns a List<string> collection
        companyNames = new CollectionView(GetCompanyNames());//method that returns a List<string> collection
        carNames.CurrentChanged += new EventHandler(carNames_CurrentChanged);
        companyNames.CurrentChanged += new EventHandler(companyNames_CurrentChanged);  
    }

And here is one of my EventHandlers.

void carNames_CurrentChanged(object sender, EventArgs e)
    {
        if ((sender as CollectionView).CurrentItem != null)
        {
            //Do Something          
        }
    }

And finally here is my combobox in my view.

<ComboBox Margin="5"
       SelectedValue="{Binding Path=SelectedCar}"  
       ItemsSource="{Binding carNames}"
       IsSynchronizedWithCurrentItem="True"
       x:Name="cmbCar" />

So my question is! How can I prevent my EventHandler being fired when the view load.

Any help is appreciated.

Cheers.

Noel

Upvotes: 1

Views: 1713

Answers (1)

jnovo
jnovo

Reputation: 5789

In order to avoid the handler being called on load you'd need to make sure it is set after the view is loaded. How is your ViewModel being instanced? If it suits your design, you may create it after the view has loaded although I wouldn't recommend that option.

A better option -although not very elegant either- may be to bind (OneWayToSource) to the the ComboBox.IsLoaded property and set the handlers when the ViewModel bound property changes to true.

As an alternative, couldn't you just watch for changes of the SelectedCar property changing and perform your logic then?

Upvotes: 1

Related Questions