我创建了一个简单的依赖属性,我想将其附加到 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));
}
我的树视图的样式如下所示:
<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>
您可以覆盖GetContainerForItemOverride https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.itemscontrol.getcontainerforitemoverride?view=windowsdesktop-6.0在你的TreeView
(是的,你需要子类化TreeView
too).
protected override DependencyObject GetContainerForItemOverride()
{
return new YourCustomTreeViewItem();
}
Note你需要覆盖GetContainerForItem
根据您的习惯TreeViewItem
如果您希望它们生成该类型的子项,也是如此。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)