2012-12-06 27 views
2

我有一个组合框绑定到一个ObservableCollection <源>。在类中有2个属性ID和类型,以及ToString()方法,其中我将ID与Type结合在一起。当我更改组合框中的类型时,它仍然显示旧的类型,但对象已更改。绑定到Combobox的ObservableCollection ToString方法不更新

public partial class ConfigView : UserControl,INotifyPropertyChanged 
{ 

    public ObservableCollection<Source> Sources 
    { 
     get { return _source; } 
     set { _source = value; 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs("Sources")); 
     } 
    } 


    public ConfigView() 
    { 
     InitializeComponent(); 
     this.DataContext = this; 
     Sources = new ObservableCollection<Source>(); 
    } 


    public ChangeSelected(){ 
     Source test = lstSources.SelectedItem as Source; 
     test.Type = Types.Tuner; 
    } 
} 

查看:

<ListBox x:Name="lstSources" Background="Transparent" Grid.Row="1" SelectionChanged="lstSources_SelectionChanged" ItemsSource="{Binding Sources, Mode=TwoWay}" /> 

来源类别:

public enum Types { Video, Tuner } 

    [Serializable] 
    public class Source: INotifyPropertyChanged 
    { 

     private int id; 

     public int ID 
     { 
      get { return id; } 
      set { id = value; 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs("ID")); 
      } 
     } 

     private Types type; 

     public Types Type 
     { 
      get { return type; } 
      set { type = value; 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs("Type")); 
      } 
     } 


     public Source(int id, Types type) 
     { 
      Type = type; 
      ID = id; 
     } 

     public override string ToString() 
     { 
      return ID.ToString("00") + " " + Type.ToString(); 
     } 

     public event PropertyChangedEventHandler PropertyChanged; 
    } 

当类型为视频组合框显示01Video当我改变类型调谐器组合框仍显示01Video但应是01Tuner。但是,当我调试对象类型更改为调谐器。

+0

这对你有价值吗? http://www.c-sharpcorner.com/UploadFile/rvemura.net/two-way-databinding-in-wpf/ – WozzeC

+0

当你用null或string.empty提升PropertyChangedEvent时,它会改变吗?像'PropertyChanged(this,new PropertyChangedEventArgs(null))'否则是Nicolas Repiquet的答案right – Jehof

+1

我刚刚添加了PropertyChanged事件以尝试是否有效。但事实并非如此。 –

回答

4

这很正常。 ListBox不可能知道当IDType更改时,ToString将返回不同的值。

你必须以不同的方式做。

<ListBox ItemsSource="{Binding ...}"> 
    <ListBox.ItemTemplate> 
    <DataTemplate> 
     <TextBlock> 
     <TextBlock Text="{Binding ID}"/> 
     <TextBlock Text=" "/> 
     <TextBlock Text="{Binding Type}"/> 
     </TextBlock> 
    </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 
+0

谢谢你完美的作品。 –

相关问题