C# WPF组合框忽略ItemsSource对象上的ToString覆盖

C# WPF组合框忽略ItemsSource对象上的ToString覆盖,c#,wpf,combobox,overriding,tostring,C#,Wpf,Combobox,Overriding,Tostring,我已将观察名单定义如下: // a named list of VariableWatchers public class WatchList : List<VariableWatcher> { private string _name; public WatchList(string name) : base() { _name = name; } public override string ToString()

我已将观察名单定义如下:

// 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;
    }
}
<ComboBox x:Name="WatchListDropdown"
          ItemsSource="{Binding Path=WatchLists}"
          VerticalAlignment="Center"
          Margin="5"/>
//变量观察程序的命名列表
公共类监视列表:列表
{
私有字符串\u名称;
公共监视列表(字符串名称):base()
{
_名称=名称;
}
公共重写字符串ToString()
{
返回_name;
}
}
我将观察列表绑定到ComboBox的ItemsSource属性,如下所示:

// 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;
    }
}
<ComboBox x:Name="WatchListDropdown"
          ItemsSource="{Binding Path=WatchLists}"
          VerticalAlignment="Center"
          Margin="5"/>

“监视列表”是指我的DataContext中的以下属性:

public IList<WatchList> WatchLists
{
    get { return _watchLists; }
}
公共IList监视列表
{
获取{return\u watchlist;}
}

除了列表中的所有条目都显示为“(Collection)”而不是_name变量外,一切都很好。我在ToString中设置了一个断点,并确认它在某个点被调用,并且返回了正确的值,但不知何故,组合框仍然显示“(Collection)”。

监视列表是监视列表的集合,不是吗?因此将调用并显示Collection.ToString()


将DisplayMemberPath指定为“name”如何?我希望它能工作:)

监视列表是监视列表的集合,不是吗?因此将调用并显示Collection.ToString()


将DisplayMemberPath指定为“name”如何?我希望它能工作:)

如果ItemsSource绑定到一个类型为
List
WatchList
,则实际显示的集合将是
VariableWatcher
的列表


如果ItemsSource绑定到
监视列表的集合
,则.ToString()应覆盖默认显示。当然,您始终可以创建一个属性
名称
,并将其设置为DisplayMember。

如果ItemsSource绑定到一个
监视列表
,它的类型为
列表
,则显示的实际集合将是
VariableWatcher
的列表


如果ItemsSource绑定到
监视列表的集合
,则.ToString()应覆盖默认显示。当然,您始终可以创建一个属性
名称
,并将其设置为DisplayMember。

不确定为什么不使用ToString()重写,但您是否考虑过改用DisplayMemberPath

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

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

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

谢谢,成功了!我也很困惑为什么它不使用ToString,因为这对我来说一直都很有效。谢谢,这很有效!我也很困惑为什么它不使用ToString,因为它以前一直对我有效。