StackPanel水平内容授权以dataTemplate为中心

时间:2019-05-21 17:23:15

标签: wpf datatemplate

<ComboBox Height="50" Width="90" Name="cmb" >
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal"  >
                <ItemsControl ItemsSource="{Binding Path=Names}"  BorderThickness="0" >
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel Width="50"    Orientation="Horizontal">

                            </StackPanel>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                </ItemsControl>
                <TextBlock Text="{Binding Path=Name}" />
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
    <ComboBox.Items>
    </ComboBox.Items>
</ComboBox>

C#

public class Example
{
    public string Name { get; set; }
    public List<string> Names { get; set; }

}

List<Example> list = new List<Example>();
Example ex = new Example();
ex.Name = "1";
ex.Names = new List<string> { "1", "2", "3" };
list.Add(ex);

Example ex1 = new Example();
ex1.Name = "2";
ex1.Names = new List<string> { "1", "2" };
list.Add(ex1);

Example ex2 = new Example();
ex2.Name = "3";
ex2.Names = new List<string> { "1" };
list.Add(ex2);

cmb.ItemsSource = list;

嗨,我在这里只是添加一个ItemsControl。和标签。如您所见,ItemsControl Binding属性是名称值。其值分别为1,2,3和1,2和1。我需要尝试像金字塔一样显示它们,那么如何将堆栈面板的内容设置为居中?

期望

  1     lablevalue
 1 2    lablevalue 
1 2 3   lablevalue

当前输出

1      lablevalue
1 2    lablevalue
1 2 3  lablevalue

1 个答案:

答案 0 :(得分:0)

您可以尝试类似的方法。使用IsSharedsizeScope和SharedSizeGroup允许跨不同网格共享列大小

<StackPanel   Grid.IsSharedSizeScope="True">
        <Grid Margin="2">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Label Grid.Column="0" Content="1"/>
            <Label Grid.Column="1" Content="2"/>
            <Label Grid.Column="2" Content="3"/>
        </Grid>
        <Grid Margin="15">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition  Width="Auto"/>

            </Grid.ColumnDefinitions>
            <Label Grid.Column="0" Content="1"/>
            <Label Grid.Column="1" Content="2"/>
        </Grid>
        <Grid Margin="20">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition />

            </Grid.ColumnDefinitions>
            <Label Grid.Column="0" Content="1"/>
        </Grid>
        <Button Margin="10" Content="Click Me" Width="200" HorizontalAlignment="Left" Click="Button_Click" />
    </StackPanel>