WPF样式中的继承反转

Rys*_*gan 3 c# wpf

我有一个包含按钮的UserControl:

<Button Content="Button"/>
Run Code Online (Sandbox Code Playgroud)

和风格:

<Style TargetType="Button">
    <Setter Property="Background" Value="Blue"/>
</Style>
Run Code Online (Sandbox Code Playgroud)

父窗口(或另一个UserControl)可以设置另一种更通用的样式:

<Style TargetType="Button">
    <Setter Property="Background" Value="Red"/>
</Style>
Run Code Online (Sandbox Code Playgroud)

结果是(很明显)父按钮将具有更一般的样式(红色),而我的用户控件将具有更具体样式(蓝色)的按钮.


我想知道如何反转这种行为,以实现像我的自定义用户控件中设置默认样式,然后可以在父控件或窗口中覆盖,如果有必要?

关键是,默认样式首先在自定义用户控件中定义,并由其父级自动覆盖.这就是我称之为反转的方式.


解决方案的可能示例如下所示:

<Style TargetType="Button" StylePriority="Default">
    <Setter Property="Background" Value="Blue"/>
</Style>
Run Code Online (Sandbox Code Playgroud)

StylePriority会表示,如果有该按钮定义没有其他的风格,那么默认的样式应适用于它.

ali*_*tor 6

您可以使用动态资源.

一个UserControl:

<UserControl x:Class="Example.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Example">
    <UserControl.Resources>
        <Style TargetType="local:UserControl1">
            <Style.Resources>
                <Style TargetType="Button" x:Key="UserControl1.DefaultButtonStyle">
                    <Setter Property="Background" Value="Red"/>
                </Style>
            </Style.Resources>
        </Style>
    </UserControl.Resources>

    <Button Content="UserControlButton" Style="{DynamicResource UserControl1.DefaultButtonStyle}"/>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

还有一个窗口:

<Window x:Class="Example.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Example">

    <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Background" Value="Blue" />
        </Style>
    </Window.Resources>

    <StackPanel>
        <local:UserControl1 >
            <local:UserControl1.Resources>
                <Style x:Key="UserControl1.DefaultButtonStyle" TargetType="Button"
                    BasedOn="{StaticResource {x:Type Button}}">
                    <Setter Property="FontSize" Value="40" />
                </Style>
            </local:UserControl1.Resources>
        </local:UserControl1>
        <Button Content="WindowButton" />
    </StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)

如果在窗口中删除控件的样式,则将应用默认的用户控件按钮样式.