是否可以添加以下代码:
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
进入Style
的{{1}} / Setter
模板?然后自动为此Grid
设置RowDefinitions
吗?
Grid
答案 0 :(得分:1)
您无法在RowDefinitions
中设置Style
属性,因为它不是依赖项属性,但您可以创建自定义Grid
类型并使用此属性:
public class CustomGrid : Grid
{
public CustomGrid()
{
RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) };
RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
}
}
<强>用法:强>
<local:CustomGrid>
<Button Grid.Row="0" Content="Button1/>
<TextBox Grid.Row="1"/>
<Button Grid.Row="2" Content="Button2/>
</local:CustomGrid>
答案 1 :(得分:0)
这样做可以解决您的问题:How to create reusable WPF grid layout
对于您的示例,您可以执行以下操作:
<Window x:Class="ReUseGridTest.MainWindow"
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"
xmlns:local="clr-namespace:ReUseGridTest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="GridItemsStyle" TargetType="ItemsControl">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<ItemsControl Style="{StaticResource GridItemsStyle}">
<Button Grid.Row="0" Content="Button1"/>
<TextBox Grid.Row="1" Text="Test"/>
<Button Grid.Row="2" Content="Button2"/>
</ItemsControl>
</Window>