使用mvvm动态创建控件

时间:2018-04-23 04:30:12

标签: c# xaml itemscontrol

我一直在尝试动态创建控件,到目前为止它正在运行。但我的问题是布局

<Grid Grid.Row="2" >
                <ItemsControl IsTabStop="False" ItemsSource="{Binding ListControls}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="120*"/>
                                        <RowDefinition Height="120*"/>
                                        <RowDefinition/>
                                    </Grid.RowDefinitions>
                                    <Label  Content="AN:" Margin="5,5,5,5" FontSize="14" VerticalContentAlignment="Center"/>
                                    <TextBox  Grid.Column="1" FontSize="14" VerticalContentAlignment="Center" Margin="5,5,5,5"/>
                                </Grid>
                            </StackPanel>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </Grid>

上面的xaml。这是布局的屏幕截图

enter image description here

如果我使用像这样的xaml

 <Grid Grid.Row="2" >
                <ItemsControl IsTabStop="False" ItemsSource="{Binding ListControls}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
                                <Label  Content="AN:" Margin="5,5,5,5" FontSize="14" VerticalContentAlignment="Center"/>
                                <TextBox  Width="100" FontSize="14" VerticalContentAlignment="Center" Margin="5,5,5,5"/>
                            </StackPanel>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </Grid>

enter image description here

但我的目标是,如果程序最大化,我希望文本框能够扩展。

如何调整xaml代码以扩展文本框?谢谢

1 个答案:

答案 0 :(得分:2)

直接使用Grid代替StackPanel也会移除Width="100"

<Grid HorizontalAlignment="Stretch">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Label Grid.Column="0"  Content="AN:" Margin="5,5,5,5" FontSize="14" VerticalContentAlignment="Center"/>
    <TextBox Grid.Column="1" FontSize="14" VerticalContentAlignment="Center" Margin="5,5,5,5"/>
</Grid>