我有一个绑定(bind)到 ObservableCollection
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。但是当我调试时,对象类型更改为 Tuner。
最佳答案
这很正常。 ListBox
不可能知道当 ID
或 Type
更改时 ToString
会返回不同的值。
你必须采取不同的做法。
<ListBox ItemsSource="{Binding ...}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock Text="{Binding ID}"/>
<TextBlock Text=" "/>
<TextBlock Text="{Binding Type}"/>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
关于c# - 绑定(bind)到 Combobox ToString 方法的 ObservableCollection 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13741482/