c# - 绑定(bind)到 Combobox ToString 方法的 ObservableCollection 不更新

标签 c# .net wpf .net-4.0

我有一个绑定(bind)到 ObservableCollection 的组合框。在类中有 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。但是当我调试时,对象类型更改为 Tuner。

最佳答案

这很正常。 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>

关于c# - 绑定(bind)到 Combobox ToString 方法的 ObservableCollection 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13741482/

相关文章:

c# - 尽管有一个实例,随机变量选择相同的值

c# - 如何从 Windows 窗体中的给定 url 下载文件到特定路径?

c# - Entity Framework 故意禁用自动增量

c# - 紧凑框架 2.0 的 Environment.NewLine 等价物

javascript - 当 View 中的函数完成时重新加载部分 View ?

c# - 使用 C# 程序从 praat 获取值

.net - Linq:Select 和Where 之间有什么区别

c# - 如何检测嵌套属性的变化?

.net - 扩展器作为 ListView 项目

c# - 获取数据网格中所选项目的行索引