我想让我的 WPF Listbox(数据绑定)生成子类 ListboxItems 而不是常规的 ListboxItems。在这种情况下,DataTemplate 是不够的,因为我需要子类 ListBoxItems 的一些自定义属性。
有没有办法让 ListBox 为绑定数据生成 mySubClassedListBoxItem 项?
谢谢,巴特
我想让我的 WPF Listbox(数据绑定)生成子类 ListboxItems 而不是常规的 ListboxItems。在这种情况下,DataTemplate 是不够的,因为我需要子类 ListBoxItems 的一些自定义属性。
有没有办法让 ListBox 为绑定数据生成 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);
}
// ...
}