我试图在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>
即使添加了CurrencyCellStyle样式,我也希望能够做Style="{StaticResource PlusMinusExpander}"
。
我在网上看到过类似的问题,但是他们的解决方案都没有对我有用。有没有办法同时使用Style和ResourceDictionary?
答案 0 :(得分:3)
Window.Resources
属性的类型为ResourceDictionary
,因此不能将两种不同类型的XAML元素作为兄弟。相反,您应该:
ResourceDictionary
放入Window.Resources
属性中,并将Style
写入ResourceDictionary
内。x:Key
中删除ResourceDictionary
属性。<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>