2014-10-27 91 views
0

我有這個組合框:ComboBox項犯規更新

<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

在視圖模型中發佈相關代碼。 – 2014-10-27 07:04:13

+0

@SriramSakthivel我做到了 – Nataly87 2014-10-27 07:31:10

回答

1

我看到了問題。出於某種原因,當Binding框架已經處於通知內時,它忽略了屬性更改通知。

作爲解決方法,您可以通過異步執行來推遲屬性更改。這按預期工作。

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

,請務必讓NotifyPropertyChanged( 「FlightMode」)時,FlightMode屬性設置的旋鈕對象。