有一个数据绑定WPF Listbox生成子类ListboxItems [英] Have a databound WPF Listbox generate subclassed ListboxItems

查看:108
本文介绍了有一个数据绑定WPF Listbox生成子类ListboxItems的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的WPF Listbox,它是数据绑定,生成子类ListboxItem而不是常规ListboxItems。在这种情况下,DataTemplate不够,因为我需要一些子类ListBoxItem的自定义属性。



有没有办法让ListBox生成绑定数据的mySubClassedListBoxItem项

谢谢,
Bart

解决方案

你需要创建您自己的ListBox子类,以便您可以覆盖创建容器的方法,例如

  public class MyListBox:ListBox 
{
public MyListBox()
{
//应该获得默认样式&模板,因为样式不被继承
Style = FindResource(typeof(ListBox))as Style;
}

protected override DependencyObject GetContainerForItemOverride()
{
var container = new MyListBoxItem();
返回容器;
}


public class MyListBoxItem:ListBoxItem
{
public MyListBoxItem()
{
Style = FindResource (ListBoxItem))作为样式;
//要轻松看到这些是自定义ListBoxItems:
// TextElement.SetForeground(this,Brushes.Red);
}

// ...
}


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

    // ...
}

这篇关于有一个数据绑定WPF Listbox生成子类ListboxItems的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆