开发者

Have a databound WPF Listbox generate subclassed ListboxItems

I would like to have my WPF Listbox, which is databound, generate subclassed ListboxItems instead of the regular List开发者_如何学运维boxItems. In this case, a DataTemplate is not sufficient because I need some custom properties for the subclassed ListBoxItems.

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

Thanks, Bart


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);
    }

    // ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜