我有一个包含按钮的用户控件:
<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/