【问题标题】:Have a databound WPF Listbox generate subclassed ListboxItems让数据绑定 WPF Listbox 生成子类 ListboxItems
【发布时间】:2023-03-19 05:30:01
【问题描述】:
我想让我的 WPF Listbox(数据绑定)生成子类 ListboxItems 而不是常规 ListboxItems。在这种情况下,DataTemplate 是不够的,因为我需要一些子类 ListBoxItems 的自定义属性。
有没有办法让 ListBox 为绑定数据生成 mySubClassedListBoxItem 项?
谢谢,
巴特
【问题讨论】:
标签:
wpf
data-binding
listbox
subclass
【解决方案1】:
您需要创建自己的 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);
}
// ...
}