WPF ComboBox忽略ToString覆盖ItemsSource对象

hyp*_*man 1 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我将WatchLists列表绑定到ComboBox的ItemsSource属性,如下所示:

<ComboBox x:Name="WatchListDropdown"
          ItemsSource="{Binding Path=WatchLists}"
          VerticalAlignment="Center"
          Margin="5"/>
Run Code Online (Sandbox Code Playgroud)

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

public IList<WatchList> WatchLists
{
    get { return _watchLists; }
}
Run Code Online (Sandbox Code Playgroud)

一切都很好,除了列表中的所有条目都显示为"(Collection)"而不是_name变量.我在ToString中放置了一个断点,并确认它在某个时刻被调用,并返回正确的值,但不知何故,ComboBox仍显示"(Collection)".

Joe*_*Joe 5

不知道为什么它没有使用ToString()覆盖,但您是否考虑过使用DisplayMemberPath?

<ComboBox x:Name="WatchListDropdown"
      ItemsSource="{Binding Path=WatchLists}"
      VerticalAlignment="Center"
      DisplayMemberPath="Name"
      Margin="5"/>
Run Code Online (Sandbox Code Playgroud)

当然,您需要调整对象,因为绑定需要公共属性或依赖属性.

private string _name;
public string Name { get { return _name; } set { _name = value; } }
Run Code Online (Sandbox Code Playgroud)