我想让我的 WPF 列表框(数据绑定(bind))生成子类 ListboxItems,而不是常规的 ListboxItems。在这种情况下,DataTemplate 是不够的,因为我需要子类 ListBoxItems 的一些自定义属性。
有没有办法让 ListBox 为绑定(bind)数据生成 mySubClassedListBoxItem 项?
谢谢, 巴特
最佳答案
您需要创建自己的 ListBox 子类,以便可以重写创建容器的方法,例如
public class MyListBox : ListBox
{
public MyListBox()
{
// Should get the default style & template since styles are not inherited
Style = FindResource(typeof(ListBox)) as Style;
}
protected override DependencyObject GetContainerForItemOverride()
{
var container = new MyListBoxItem();
return container;
}
}
public class MyListBoxItem : ListBoxItem
{
public MyListBoxItem()
{
Style = FindResource(typeof(ListBoxItem)) as Style;
// To easily see that these are custom ListBoxItems:
// TextElement.SetForeground(this, Brushes.Red);
}
// ...
}
关于wpf - 让数据绑定(bind) WPF Listbox 生成子类 ListboxItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1581934/