Xaml继承样式

4

在XAML中是否有一种方法可以设置一个适用于所有控件的样式? 例如,我想为所有控件添加一个边距。 我可以通过将TargetType更改为Button、CheckBox等为每种类型添加一个样式。但是,我希望像下面所示一样将其设置为适用于从Control继承的所有类型:

<UserControl x:Class="MyPanel"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    Height="300" Width="300">
    <UserControl.Resources>
        <Style TargetType="Control">
            <Setter Property="Margin" Value="3"/>
        </Style>
</UserControl.Resources>
    <StackPanel>
        <Button>My Button</Button>
        <CheckBox>My Checkbox</CheckBox>
    </StackPanel>
</UserControl>
1个回答

15

没有直接的方法可以做到这一点。但是,你可以定义一个基础样式并从中继承:

<Style x:Key="BaseStyle">
    <Setter Property="FrameworkElement.Margin" Value="3"/>
</Style>

<Style TargetType="Button" BasedOn="{StaticResource BaseStyle}">
</Style>

<Style TargetType="TextBox" BasedOn="{StaticResource BaseStyle}">
</Style>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接