2009-10-17 57 views
2

我想有我WPF列表框,这是数据绑定,生成子类ListboxItems,而不是常规ListboxItems。在这种情况下,DataTemplate是不够的,因为我需要为子类ListBoxItems的一些自定义属性。有一个数据绑定列表框WPF子类生成ListboxItems

有没有办法有对数据绑定列表框生成mySubClassedListBoxItem项目?

感谢, 巴特

回答

3

您需要创建自己的列表框的子类,所以你可以重写它创建容器的制造方法,例如

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

    // ... 
}