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

心已入冬 提交于 2019-12-23 17:21:44

问题


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>

回答1:


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.



来源:https://stackoverflow.com/questions/9470190/how-to-subclass-wpfs-treeviewitem-and-use-it-in-a-treevview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!