c# - WPF 样式中的继承反转

标签 c# wpf

我有一个包含按钮的用户控件:

<Button Content="Button"/>

还有一种风格:

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

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

<Style TargetType="Button">
    <Setter Property="Background" Value="Red"/>
</Style>

结果是(很明显)父按钮将具有更通用的样式(红色),而我的用户控件将具有更特定样式的按钮(蓝色)。


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

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


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

<Style TargetType="Button" StylePriority="Default">
    <Setter Property="Background" Value="Blue"/>
</Style>

StylePriority 可以指示如果没有为该按钮定义其他样式,则应将默认样式应用于它。

最佳答案

您可以使用动态资源。

用户控件:

<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>

还有一个窗口:

<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>

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

关于c# - WPF 样式中的继承反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17919627/

相关文章:

wpf - WPF 中第二次加载时不下载图像

c# - 如何将匿名类型转换为类型?

c# - WPF:是否有 Telerik DataFilter 的免费(开源)替代品?

c# - 使用触发器更改已绑定(bind)到 View 模型的属性

c# - 有没有办法自定义 Thinktecture.IdentityServer.v2 登录页面?

c# - 在 WPF/C# 中以编程方式更改边距

c# - 列表框中的项目溢出

c# - SharpPcap 获取进程名称

c# - XmlSerializer 需要 XmlInclude 用于具有通用约束的公共(public)方法,如果在另一个程序集中键入并且要求该类型是可序列化的!

c# - 使用带有 c dll 的后台工作程序