c# - 在 WPF 中将 ResourceDictionary 与其他样式一起使用

标签 c# wpf xaml resourcedictionary

我正在尝试在我的 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/

相关文章:

c# - 如何以编程方式分配样式

c# - WPF 用户控件项未显示

c# - WPF:具有在按下 Enter 键时触发的事件的 TextBox

c# - 将位图转换为 ImageSource 后资源 png 质量下降

c# - 对列表框中的列表项进行 HitTest

c# - 嵌套 UserControl 的自动调整大小不起作用

xaml - 转换器无法将类型 'Windows.Foundation.String' 的值转换为类型 'ImageSource'

c# - 如何在代码隐藏中调用 Prism 事件

c# - 虚拟事件如何在 C# 中工作?

C# 继承 : casting of parent object to child