c# - WPF ComboBox 忽略 ItemsSource 对象上的 ToString 覆盖

标签 c# wpf combobox overriding tostring

我定义了 WatchList 如下:

// a named list of VariableWatchers
public class WatchList : List<VariableWatcher>
{
    private string _name;

    public WatchList(string name) : base()
    {
        _name = name;
    }

    public override string ToString()
    {
        return _name;
    }
}

我将 WatchList 列表绑定(bind)到 ComboBox 的 ItemsSource 属性,如下所示:

<ComboBox x:Name="WatchListDropdown"
          ItemsSource="{Binding Path=WatchLists}"
          VerticalAlignment="Center"
          Margin="5"/>

“WatchLists”指的是我的 DataContext 中的以下属性:

public IList<WatchList> WatchLists
{
    get { return _watchLists; }
}

除了列表中的所有条目都显示为“(集合)”而不是 _name 变量外,一切都很好。我在 ToString 中放置了一个断点,并确认它在某个时刻被调用,并返回正确的值,但 ComboBox 仍然以某种方式显示“(Collection)”。

最佳答案

不确定为什么不使用 ToString() 覆盖,但您是否考虑过使用 DisplayMemberPath?

<ComboBox x:Name="WatchListDropdown"
      ItemsSource="{Binding Path=WatchLists}"
      VerticalAlignment="Center"
      DisplayMemberPath="Name"
      Margin="5"/>

当然,您需要调整对象,因为绑定(bind)需要公共(public)属性或依赖属性。

private string _name;
public string Name { get { return _name; } set { _name = value; } }

关于c# - WPF ComboBox 忽略 ItemsSource 对象上的 ToString 覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13056372/

相关文章:

c# - FieldOptional FileHelpers 必须标记为可选,因为前一个字段已标记为可选

c# - 运行时无法加载文件或程序集 'Newtonsoft.Json, Version=6.0.0.0 ...",间接依赖程序集继续寻找旧版本

c# - 在类库中嵌入 exe 文件

c# - 如何添加动态控件而不是静态控件?

c# - 在 WPF 中为组合框设置默认值

c# - HangFire "Cannot access a disposed object. Object name: ' SqlDelegatedTransaction'”

WPF MVVM WCF 客户端/服务器架构

javascript - 使 jQuery ComboBox 的选项不可选择

C# Combobox (Dropdownstyle = Simple) -- 如何在键入时选择项目

c# - 工具栏中的按钮自动对齐