[英]ObservableCollection bound to Combobox ToString methode doesn't update
我有一个绑定到ObservableCollection <Source>的组合框。 在该类中,有2个属性ID和Type,以及ToString()方法,其中将ID与Type结合在一起。 当我在组合框中更改类型时,它仍显示旧类型,但对象已更改。
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。 但是,当我调试对象类型更改为调谐器。
那是完全正常的。 当ID
或Type
更改时, ListBox
可能无法知道ToString
将返回不同的值。
您必须做不同的事情。
<ListBox ItemsSource="{Binding ...}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock Text="{Binding ID}"/>
<TextBlock Text=" "/>
<TextBlock Text="{Binding Type}"/>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.