Have WPF Listbox Data Binding Generates ListboxItems Subclasses

I would like to have my WPF Listbox, which is a database binding, generate subclasses of ListboxItems instead of regular ListboxItems. In this case the DataTemplate is not enough because I need some custom properties to subclass ListBoxItems.

Is there a way for the ListBox to generate mySubClassedListBoxItem items for related data?

Thanks, Bart

+2


source to share


1 answer


You need to create your own ListBox subclass so that you can override the method that creates the container eg.



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

    // ...
}

      

+3


source







All Articles