wpf - 让数据绑定(bind) WPF Listbox 生成子类 ListboxItems

标签 wpf data-binding listbox subclass

我想让我的 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/

相关文章:

WPF:使用 WPF 扩展中的 PropertyGrid

WPF 可编辑组合框

wpf - 为 UserControl 设置 Canvas.Top

python - Tkinter:列表框分隔符、禁用项、键盘导航?

asp.net-mvc-3 - MVC3 Razor - 列表框预选不起作用

c# - 如何更改特定单元格的 DataGridTemplateColumn DataTemplate 元素的属性

c# - WPF - 如何将控件的位置绑定(bind)到当前鼠标位置?

xamarin.forms - 如何在选择器的所选项目更改时触发命令

c# - 如何在 DataBind 后隐藏 GridView 中的列?

C# ListBox 从文本文件导入时崩溃