我有一个网格,里面有一些元素:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="SomeText" Grid.Column="0" Grid.Row="0" />
<TextBox Grid.Column="1" Grid.Row="0" />
<TextBlock Text="SomeText" Grid.Column="0" Grid.Row="1" />
<TextBox Grid.Column="1" Grid.Row="1" />
<TextBlock Text="SomeText" Grid.Column="0" Grid.Row="2" />
<TextBox Grid.Column="1" Grid.Row="2" />
</Grid>
问题是它看起来很紧:
Margin 属性解决了这个问题,但我应该将此属性设置为网格内的每个元素。这是一条艰难的路。
我只想获得类似这样的设置 margin 属性一次,但不是每个元素:
最佳答案
您可以将 Margin
放入 Grid.Resources
中的隐式 Style
中。
例如
<Style x:Key="MarginStyle" TargetType="FrameworkElement">
<Setter Property="Margin" Value="5"/>
</Style>
<Style TargetType="TextBox" BasedOn="{StaticResource MarginStyle}"/>
<Style TargetType="TextBlock" BasedOn="{StaticResource MarginStyle}"/>
您还可以使用 ItemsControl
来应用通用样式。
例如
<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<!-- Panel without children here -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="FrameworkElement">
<Setter Property="Margin" Value="5"/>
</Style>
</ItemsControl.ItemContainerStyle>
<!-- Children here -->
<Label Grid.Row="0" Content="Field 1: "/>
<Label Grid.Row="1" Content="Field 2: "/>
<TextBox Grid.Column="1" Grid.Row="0"/>
<TextBox Grid.Column="1" Grid.Row="1"/>
</ItemsControl>
关于wpf - 在 XAML 中设置 Grid 或 StackPanel 元素之间的距离的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11433479/