Wpf 设置栅格和#x27;s或StackPanel';XAML中的s元素?
我有一个网格,里面有一些元素:Wpf 设置栅格和#x27;s或StackPanel';XAML中的s元素?,wpf,xaml,Wpf,Xaml,我有一个网格,里面有一些元素: <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.Colum
<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属性解决了这个问题,但我需要为网格中的每个元素设置这个属性。这是一条艰难的道路
我只想获得一次类似此设置边距属性的内容,但不是针对每个元素:
为什么不做一个标记并将其应用于元素?您可以将
边距
放入网格中的隐式样式中。参考资料
e、 g
您可以将类似的内容添加到网格的资源部分
<Grid.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Margin" Value="0,5" />
</Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Margin" Value="0,5" />
</Style>
</Grid.Resources>
或者,也可以使用填充有2个柱网轴线的垂直堆叠面板
然后只设置网格的样式我应该为网格中的每个元素手动设置样式吗?@JohnWales:不,通过设置TargetType
而不是键来隐式设置。此语法不正确,您需要设置TargetType=“{x:Type TextBox}”@jimmyjambles:不,谢谢!但我没有名声加上你。
<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>
<Grid.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Margin" Value="0,5" />
</Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Margin" Value="0,5" />
</Style>
</Grid.Resources>