Nataly87
Nataly87

Reputation: 243

Combobox Item doesnt update

i have this combobox:

<ComboBox ItemsSource="{Binding Knobs.AvailableFlightModes}" 
    SelectedValue="{Binding Knobs.FlightMode}" SelectedValuePath="Value" />

the data context implements INotifyPropertyChanged interface, and in the code i check if the FlightMode that was selected is ok, and if not i change it. the problem is when i change it back the displayed item doesent change back. for example: the selected item was item1, the user changed it to item2, and it changed back to item1, but the display is still item2.

here is an example code:

public class Names : INotifyPropertyChanged 
{
    public Names()
    {
        m_NewList = new ObservableCollection<thing>();
        foreach (things item in Enum.GetValues(typeof(things)))
        {
            m_NewList.Add(new thing() { Enum = item });
        }

        this.PropertyChanged += new PropertyChangedEventHandler(Names_PropertyChanged);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    void Names_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "Stuff" && m_Stuff != things.a)
        {
            Stuff = things.a;
        }
    }

    private readonly ObservableCollection<thing> m_NewList;
    public ObservableCollection<thing> NewList { get { return m_NewList; } }

    private things m_Stuff;
    public things Stuff
    {
        get { return m_Stuff; }
        set
        {
            m_Stuff = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Stuff"));
        }
    }
}

public class thing
{
    public things Enum { get; set; }
    public string Just { get; set; }
    public override string ToString()
    {
        return Enum.ToString();
    }
}

public enum things { a, b, c, d }

-

<ComboBox ItemsSource="{Binding NewList}" SelectedValuePath="Enum" SelectedValue="{Binding Stuff}" />

Upvotes: 0

Views: 71

Answers (2)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

I see the problem. For some reason it seems Binding framework ignores the property change notification when it is already inside of the notification.

As a workaround, you can defer the property change by doing it asynchronously. That works as expected.

void Names_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
    {
        if (e.PropertyName == "Stuff" && m_Stuff != things.a)
        {
            Stuff = things.a;
        }
    }));
}

Upvotes: 1

furkle
furkle

Reputation: 5059

Make sure you call NotifyPropertyChanged("FlightMode") when the FlightMode property is set on the Knobs object.

Upvotes: 0

Related Questions