Have a databound WPF Listbox generate subclassed ListboxItems

后端 未结 1 621
庸人自扰
庸人自扰 2021-01-22 18:15

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 bec

相关标签:
1条回答
  • 2021-01-22 19:03

    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 讨论(0)
提交回复
热议问题