我已经创建了一个简单的依赖属性,想要将其附加到TreeViewItem上。我已经为其他控件(如按钮)完成了类似的操作,但是无法在TreeView中使用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));
}
我的树视图的样式看起来像这样:
<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>