wpftreeviewtreeviewitem

How to Subclass WPF's TreeViewItem and use it in a treevview


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>

I am using it like:

    <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>

Solution

  • 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.