让数据绑定 WPF Listbox 生成子类 ListboxItems [英] Have a databound WPF Listbox generate subclassed ListboxItems

查看:20
本文介绍了让数据绑定 WPF Listbox 生成子类 ListboxItems的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的 WPF Listbox(数据绑定)生成子类 ListboxItems 而不是常规 ListboxItems.在这种情况下,DataTemplate 是不够的,因为我需要一些子类 ListBoxItems 的自定义属性.

I would like to have my WPF Listbox, which is databound, generate subclassed ListboxItems instead of the regular ListboxItems. In this case, a DataTemplate is not sufficient because I need some custom properties for the subclassed ListBoxItems.

有没有办法让 ListBox 为绑定数据生成 mySubClassedListBoxItem 项?

Is there a way to have the ListBox generated mySubClassedListBoxItem items for the bound data?

谢谢,巴特

推荐答案

您需要创建自己的 ListBox 子类,以便覆盖创建容器的方法,例如

You need to create your own subclass of ListBox so you can override the method which creates the container, e.g.

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 Listbox 生成子类 ListboxItems的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆