如何使样式扩展但不覆盖其他样式

本文关键字:样式 覆盖 其他 扩展 何使 | 更新日期: 2023-09-27 18:34:39

在当前窗口中,我有一个带有多个控件(标签,文本框,按钮(的网格。常规样式在 App.xaml 中设置。每个控件的扩展在网格资源中设置。每个控件可见性都由视图模型属性值确定。不要将每个控件可见性绑定到它(它使用自定义转换器,这会导致大量重复(我希望拥有"MyVisible1"样式。

问题是如果我应用这种样式,它会与其他属性重叠。我应该在"基于"中使用什么值?或者我还能做些什么来实现它?

<Grid>
    <Grid.Resources>
        <Style TargetType="{x:Type Control}" x:Key="MyVisible1">
            <Setter Property="Visibility" Value="{Binding ...}" />
        </Style>
        <Style TargetType="Label" BasedOn="{StaticResource {x:Type Label}}">
            <Setter Property="HorizontalAlignment" Value="Right" />
        </Style>
        <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
            <Setter Property="Width" Value="80" />
            <Setter Property="HorizontalAlignment" Value="Left" />
        </Style>
        <Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
            <Setter Property="Width" Value="45" />
            <Setter Property="HorizontalAlignment" Value="Right" />
        </Style>
    </Grid.Resources>
    <TextBox Grid.Column="0" Grid.Row="0" Style="{StaticResource MyVisible1}"/>
</Grid>

如何使样式扩展但不覆盖其他样式

我能想象到你可以做到这一点的唯一方法是为此定义一个本地隐式Style

<Style TargetType="{x:Type Control}">
    <Setter Property="Visibility" Value="{Binding ...}" />
</Style>

通过定义x:Key,此Style将隐式应用于扩展Control类的所有控件,并通过在本地声明它,它将仅适用于当前焦点范围内的那些元素。因此,在Grid.Resources部分中定义它将隐式地将其应用于该Grid中的所有控件。然后,您可以自由地将所需的任何其他Style应用于这些控件。