扩展样式而不在基本样式中设置x:Key属性

时间:2017-09-14 11:44:46

标签: wpf

我有一个设计WPF按钮的文件MyButtonStyles.xaml。此文件使用样式设置一些颜色和字体:

<ResourceDictionary xmlns......>
    <Style BasedOn="{StaticResource {x:Type Button}} TargetType="{x:Type Button}">
        <Setter Property="Foreground" Value="Blue" />
        <Setter Property="FontSize" Value="22" />
    </Style>
</ResourceDictionary>

此按钮用于两个xaml文件。一个显示按上述风格设计的按钮。这是自动发生的,因为上述样式具有相应的TargetType并且没有x:Key属性。

在另一个xaml文件中我也使用此按钮,但上面的样式应该由另一个setter属性扩展。通过合并字典并基于它的原始样式来实现这一点:

<ResourceDictionary>
    <ResourceDictionary.MergedDictionary>
        <ResourceDictionary Source="MyButtonStyles.xaml" />
    <ResourceDictionary.MergedDictionary>

    <Style BasedOn="ButtonStylesOrig" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Green" />
    </Style>
</ResourceDictionary>

但是为此,我必须在基本样式中添加x:Key属性(ButtonStylesOrig)。这意味着在第一个使用按钮的xaml中,基本样式将不再应用。

是否有可能在不失去全局范围的情况下扩展样式(例如,不使用x:Key)?

2 个答案:

答案 0 :(得分:1)

您不能将同一类型的多个默认样式组合为单个资源范围。但是,可以在嵌套资源范围中构建默认样式。

假设您将MyButtonStyles.xaml合并到App.xaml资源中。然后,您可以将带有附加设置器的第二个样式放入Window.Resources或其他更深层次的嵌套资源中,它将组合正确的隐式样式。

一个更本地化的例子:

<Grid>
    <Grid.Resources>
        <ResourceDictionary Source="MyButtonStyles.xaml"/>
    </Grid.Resources>
    <Grid>
        <Grid.Resources>
            <Style BasedOn="{StaticResource {x:Type Button}}" TargetType="{x:Type Button}">
                <Setter Property="Background" Value="Green" />
            </Style>
        </Grid.Resources>
        <Button VerticalAlignment="Top" Margin="20">Both styles</Button>
    </Grid>
    <Button VerticalAlignment="Center" Margin="20">ExampleDictionary style</Button>
</Grid>

答案 1 :(得分:1)

这有效:

<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="MyButtonStyles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Grid.Resources>
            <Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
                <Setter Property="Background" Value="Green" />
            </Style>
        </Grid.Resources>

        <Button Content="Button" />
    </Grid>
</Window>

关键是不要覆盖将基本样式合并到的同一资源字典中的资源:

WPF Using multiple Resource Dictionaries from multiple projects

相关问题