如何子类化 WPF 的 TreeViewItem 并在 treevview 中使用它

use*_*533 5 wpf treeview treeviewitem

我创建了一个简单的依赖属性,我想将其附加到 TreeViewitem,我对其他控件(例如按钮)做了类似的事情,但无法弄清楚如何在树视图中使用 TreeViewItem 而不丢失我定义的样式。通过下面的代码,我得到“用于类型‘ErrorTreeViewItem’的样式不能应用于类型‘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));
}
Run Code Online (Sandbox Code Playgroud)

我的树视图的样式如下所示:

      <Style TargetType="me:ErrorTreeViewItem">

        <Style.Resources>
           ...
        </Style.Resources>
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TreeViewItem">
                ...
            </Setter.Value>
        </Setter>
Run Code Online (Sandbox Code Playgroud)

我使用它的方式如下:

    <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>
Run Code Online (Sandbox Code Playgroud)

H.B*_*.B. 1

TreeView将创建默认值TreeViewItems,因此您首先需要让它创建您的树视图项目。为此,您需要子类化TreeView并重写PrepareContainerForItem以返回 的新实例ErrorTreeViewItem