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。但是,當我調試對象類型更改爲調諧器。
這對你有價值嗎? http://www.c-sharpcorner.com/UploadFile/rvemura.net/two-way-databinding-in-wpf/ – WozzeC
當你用null或string.empty提升PropertyChangedEvent時,它會改變嗎?像'PropertyChanged(this,new PropertyChangedEventArgs(null))'否則是Nicolas Repiquet的答案right – Jehof
我剛剛添加了PropertyChanged事件以嘗試是否有效。但事實並非如此。 –