使用WPF样式设置所有控件和文本块的边距

时间:2019-02-24 00:44:43

标签: wpf xaml wpf-style

我想使用样式设置所有控件和TextBlocks的边距。这是我的不使用样式的窗口XAML:

<Window x:Class="Window2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="Window2" Height="150" Width="300">
    <StackPanel>
        <TextBlock Margin="5" Text="Test" Foreground="White"/>
        <TextBox Margin="5">Test</TextBox>
        <Button Margin="5">Test</Button>
    </StackPanel>
</Window>

这是预期的结果:

enter image description here

我确实知道TextBlock是FrameWorkElement,而TextBox&Button是控件(它是FrameWorkElement)。在FrameWorkElement上引入了Margin属性,因此我尝试在FrameWorkElement上设置Margin失败了:

<Window x:Class="Window2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="Window2" Height="150" Width="300">
    <StackPanel>
        <StackPanel.Resources>
            <Style TargetType="FrameworkElement">
                <Setter Property="Margin" Value="5"/>
            </Style>
        </StackPanel.Resources>
        <TextBlock Text="Test" Foreground="White"/>
        <TextBox>Test</TextBox>
        <Button>Test</Button>
    </StackPanel>
</Window>

enter image description here

如何使用样式为所有框架元素设置边距?

1 个答案:

答案 0 :(得分:1)

 <Window.Resources>
        <!-- One style for each *type* of control on the window -->
        <Style TargetType="TextBox">
            <Setter Property="Margin" Value="10"/>
        </Style>
        <Style TargetType="TextBlock">
            <Setter Property="Margin" Value="10"/>
        </Style>
    </Window.Resources>
    <StackPanel>
        <TextBox Text="TextBox"/>
        <TextBlock Text="TextBlock"/>
    </StackPanel>