2

データバインドされたWPFリストボックスで、通常のListboxItemsの代わりにサブクラス化されたListboxItemsを生成したいと思います。この場合、サブクラス化されたListBoxItemsにいくつかのカスタムプロパティが必要なため、DataTemplateでは不十分です。

バインドされたデータのmySubClassedListBoxItemアイテムをListBoxで生成する方法はありますか?

ありがとう、バート

4

1 に答える 1

3

コンテナを作成するメソッドをオーバーライドできるように、ListBox の独自のサブクラスを作成する必要があります。

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

    // ...
}
于 2011-06-13T23:52:21.970 に答える