【发布时间】:2021-10-14 09:00:00
【问题描述】:
所以,我在使用自定义 treeviewitem:s 创建自定义树视图时遇到了这个问题,其中 ItemContainerStyle 通过从自定义样式加载样式被清除。
它是这样工作的。我有基于 TreeViewItem 的自定义 MyTreeViewItem。
<TreeViewItem x:Class="UI.MyTreeViewItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<TreeViewItem.Resources>
<Style x:Key="MyTreeViewItemStyle" TargetType="TreeViewItem">
<Setter Property="Background" Value="#AEFFC1" />
</Style>
</TreeViewItem.Resources>
</TreeViewItem>
如您所见,我在这里只设置了一个简单的颜色,以确保它自己的样式有效。除非我在后面的代码中这样做,否则这将永远不会加载。
编辑:我知道不需要将诸如着色之类的内容放在这里,因为这里本来是打算放一个模板的。自从注意到真正起作用以来,我只是把它剥离到骨头上,以确保我放了一些超级简单的东西,我知道它应该可以工作,以防万一它是因为它本身的模板。
public partial class MyTreeViewItem : TreeViewItem
{
public MyTreeViewItem()
{
InitializeComponent();
this.Loaded += MyTreeViewItem_Loaded;
}
private void MyTreeViewItem_Loaded(object sender, RoutedEventArgs e)
{
this.Style = Resources["MyTreeViewItemStyle"] as Style;
}
}
这很有效。已经多次将它与其他控件一起使用,以便为需要加载的控件自定义样式,而不必费心一遍又一遍地“重新设置样式”。
我怎么会遇到这个问题。这就是 ItemContainerStyle 用于这种自定义样式控制器的时候。
<local:BaseTreeView x:Class="My.Navigator.NavigatorTreeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ui="clr-namespace:UI;assembly=BaseCode"
d:DesignHeight="450" d:DesignWidth="800">
<ui:MyTreeView ItemsSource="{Binding Path=Nodes}">
...
<ui:MyTreeView.ItemContainerStyle>
<Style TargetType="{x:Type ui:MyTreeViewItem}">
<Setter Property="FontWeight" Value="Normal" />
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<EventSetter Event="Selected" Handler="TreeView_SelectedItemChanged" />
<EventSetter Event="Expanded" Handler="TreeView_NodeExpanded" />
<EventSetter Event="Collapsed" Handler="TreeView_NodeCollapsed" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
</ui:MyTreeView.ItemContainerStyle>
</ui:MyTreeView>
</local:BaseTreeView>
您在上面看到的这个ui:MyTreeView.ItemContainerStyle 在样式加载后将被this.Style = Resources["MyTreeViewItemStyle"] as Style; 完全忽略在MyTreeViewItem_Loaded 中。
这意味着这些 Setter、EventSetter 和 Trigger 根本不会触发,因为它们仍然需要能够作为附加规则添加。
如何解决这个问题,以便可以加载自定义控件中的预定义样式,并且通过使用此控件,您仍然可以连接独特的规则,例如上面没有预定义的否决它们?
【问题讨论】:
标签: c# wpf wpf-style itemcontainerstyle