我定义了 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/