我有这个组合框:
<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}" />
答案 0 :(得分:1)
我看到了问题。出于某种原因,当绑定框架已经在通知内部时,它似乎忽略了属性更改通知。
作为一种解决方法,您可以通过异步执行来推迟属性更改。这符合预期。
void Names_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
{
if (e.PropertyName == "Stuff" && m_Stuff != things.a)
{
Stuff = things.a;
}
}));
}
答案 1 :(得分:0)
确保在Knobs对象上设置FlightMode属性时调用NotifyPropertyChanged(“FlightMode”)。