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

时间:2013-10-10 09:45:14

标签: c# wpf xaml

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

问题是,如果我应用此样式,它会重叠其他属性。我应该在“BasedOn”中使用什么价值?或者我还能做些什么来实现它?

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

1 个答案:

答案 0 :(得分:0)

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

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

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