绑定到Combobox ToString方法的ObservableCollection不会更新

时间:2012-12-06 10:21:53

标签: c# .net wpf .net-4.0

我有一个绑定到ObservableCollection< Source>的Combobox。在类中有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;
    }

当Type为Video时,当我将类型更改为Tuner时,Combobox会显示01Video,Combobox仍会显示01Video但它应该是01Tuner。但是当我调试时,Object类型变为Tuner。

1 个答案:

答案 0 :(得分:4)

这是完全正常的。当ListBoxToString发生变化时,ID无法知道Type会返回不同的值。

你必须采用不同的方式。

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