Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何轻松设置网格布局内容的默认对齐方式?_C#_Wpf - Fatal编程技术网

C# 如何轻松设置网格布局内容的默认对齐方式?

C# 如何轻松设置网格布局内容的默认对齐方式?,c#,wpf,C#,Wpf,目前,一些示例代码可能是这样的: <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Button Content="Click me" Name="MainButton" Click="MainButton

目前,一些示例代码可能是这样的:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Button Content="Click me" Name="MainButton" Click="MainButton_Click"  Grid.Column="0" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center" />
    <TextBlock Name="CounterBlock" Text="Count: 0" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
甚至:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" DefaultHorizontalAlignment="Center" />
        <RowDefinition Height="*" DefaultHorizontalAlignment="Center" />
    </Grid.RowDefinitions>
</Grid>


我是否遗漏了什么,或者这不是一个简单的过程?谢谢

在网格级别没有类似ContentAlignment的属性。可以为子元素设置样式。 您可以将其添加到网格中

<Grid.Resources>
    <Style x:Key="alignmentStyle" TargetType="{x:Type FrameworkElement}">
        <Setter Property="HorizontalAlignment" Value="Center"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
    </Style>
    <Style TargetType="Button" BasedOn="{StaticResource alignmentStyle}"/>
    <Style TargetType="TextBlock" BasedOn="{StaticResource alignmentStyle}"/>
</Grid.Resources>

正如您在上面看到的,我们必须显式地为每种类型设置样式,因为像FrameworkElement这样的基类型单独设置是不起作用的


如果您只有很少的元素,这可能没有多大帮助。或者您有许多元素,几乎每个元素都是不同类型的。

将样式声明为网格资源怎么样?+1用于继承和隐式样式的使用。另一种方法是将网格子类化或实现自定义面板,以便根据需要安排子级,但这对于这个问题来说太复杂了。
<Grid.Resources>
    <Style x:Key="alignmentStyle" TargetType="{x:Type FrameworkElement}">
        <Setter Property="HorizontalAlignment" Value="Center"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
    </Style>
    <Style TargetType="Button" BasedOn="{StaticResource alignmentStyle}"/>
    <Style TargetType="TextBlock" BasedOn="{StaticResource alignmentStyle}"/>
</Grid.Resources>