组合框项不更新

本文关键字:更新 组合 | 更新日期: 2023-09-27 18:28:06

我有这个组合框:

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

数据上下文实现INotifyPropertyChanged接口,在代码中,我检查所选的FlightMode是否正常,如果不正常,我将更改它。问题是,当我将其更改回时,显示的项目不会更改回。例如:所选项目为item1,用户将其更改为item2,然后又更改回item1,但显示内容仍然为item2。

这是一个示例代码:

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}" />

组合框项不更新

我看到了问题。由于某种原因,当属性更改通知已经在通知中时,绑定框架似乎会忽略它。

作为一种变通方法,您可以通过异步方式推迟属性更改。正如预期的那样。

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

确保在Knobs对象上设置FlightMode属性时调用NotifyPropertyChanged("FlightMode")。