如何子类化 WPF 的 TreeViewItem 并在 treevview 中使用它 [英] How to Subclass WPF's TreeViewItem and use it in a treevview

查看:25
本文介绍了如何子类化 WPF 的 TreeViewItem 并在 treevview 中使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的依赖属性,我想将它附加到一个 treeViewitem,我已经为其他控件(例如按钮)做了类似的事情,但无法弄清楚如何在不丢失我定义的样式的情况下在树视图中使用 TreeViewItem.使用下面的代码,我得到用于类型 'ErrorTreeViewItem' 的样式不能应用于类型 'TreeViewItem'."

I have created a simple dependency property that I want to attach to a treeViewitem, I have done similar things for other controls such as buttons but cannot figure out how to use the TreeViewItem in a treeview without loosing my defined style. With the code below I get "A style intended for type 'ErrorTreeViewItem' cannot be applied to type 'TreeViewItem'."

public class ErrorTreeViewItem : TreeViewItem
{
    static ErrorTreeViewItem()
    {
    }

    public bool ErrorState
    {
        get { return (bool)GetValue(ErrorStateProperty); }
        set { base.SetValue(ErrorStateProperty, value); }
    }

    public static readonly DependencyProperty ErrorStateProperty =
        DependencyProperty.Register("ErrorState", typeof(bool), typeof(ErrorTreeViewItem), new UIPropertyMetadata(false));
}

我的树视图的样式如下:

The style of my tree view looks like:

      <Style TargetType="me:ErrorTreeViewItem">

        <Style.Resources>
           ...
        </Style.Resources>
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TreeViewItem">
                ...
            </Setter.Value>
        </Setter>

我正在使用它:

    <TreeView Name="ApplicationTree" ItemsSource="{Binding Applications}" HorizontalContentAlignment="Stretch" Background="#E8E8E8" >
        <TreeView.ItemContainerStyle>
            <Style TargetType="me:ErrorTreeViewItem" BasedOn="{StaticResource {x:Type TreeViewItem}}">
                <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
                <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            </Style>
        </TreeView.ItemContainerStyle>

推荐答案

TreeView 将创建默认的 TreeViewItems 所以你首先需要让它创建你的 树视图项.为此,您需要子类化 TreeView 并覆盖 PrepareContainerForItem 返回 ErrorTreeViewItem 的新实例.

The TreeView will create default TreeViewItems so you first need to make it create your tree view items. To do so you will need to subclass TreeView and override PrepareContainerForItem to return a new instance of ErrorTreeViewItem.

这篇关于如何子类化 WPF 的 TreeViewItem 并在 treevview 中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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