我正在尝试在我的 WPF 程序中使用 ResourceDictionary 和 Style。当我在 <Window.Resources>
中只有 ResourceDictionary 时一切正常,但只要我添加 <Style>
程序为字典显示“未找到资源”,我收到错误消息“无法解析资源“PlusMinusExpander”。”
<Window.Resources>
<Style x:Key="CurrencyCellStyle" TargetType="{x:Type DataGridCell}">
<Setter Property="Foreground" Value="#dddddd" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
</Style.Triggers>
</Style>
<ResourceDictionary x:Key="hello" Source="Assets/PlusMinusExpanderStyles.xaml" />
</Window.Resources>
<Expander Header="Plus Minus Expander" Style="{StaticResource PlusMinusExpander}" HorizontalAlignment="Right" Width="292">
<Grid Background="Transparent">
<TextBlock>Item1</TextBlock>
</Grid>
</Expander>
我希望能够做到Style="{StaticResource PlusMinusExpander}"
即使在添加 CurrencyCellStyle 样式之后。
我在网上看到过类似的问题,但他们的解决方案都不适合我。有没有办法同时使用 Style 和 ResourceDictionary?
最佳答案
Window.Resources
属性的类型是ResourceDictionary
,所以不能将两种不同类型的XAML 元素视为兄弟。相反,您应该:
- 将一个单独的
ResourceDictionary
放入Window.Resources
属性中,并在ResourceDictionary
中写入Style
。 - 从
ResourceDictionary
中删除x:Key
属性。
<FrameworkElement.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Assets/PlusMinusExpanderStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style x:Key="CurrencyCellStyle" TargetType="{x:Type DataGridCell}">
<Setter Property="Foreground" Value="#dddddd" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
</FrameworkElement.Resources>
关于c# - 在 WPF 中将 ResourceDictionary 与其他样式一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51391028/