我正在使用以下 xaml:
<ListBox Name="Lst" ItemsSource="{Binding Items}" HorizontalContentAlignment="Stretch" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" Width="500" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" BorderBrush="Black" >
<Grid >
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="Id" />
<Label Grid.Row="0" Grid.Column="1" Content="{Binding Id}" />
<Label Grid.Row="1" Grid.Column="0" Content="Name" />
<Label Grid.Row="1" Grid.Column="1" Content="{Binding Name}" />
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
和隐藏代码:
public MainWindow()
{
InitializeComponent();
DataContext = new
{
Items = new object[]
{
new {Id = 1, Name = "John"},
new {Id = 2, Name = "John Smith"},
new {Id = 3, Name = "Andrew"},
new {Id = 4, Name = "Andrew Wright"},
new {Id = 5, Name = "Arthur"},
new {Id = 6, Name = "Arthur Williams"},
new {Id = 7, Name = "another name"},
new {Id = 8, Name = "another name and surname"}
}
};
}
现在我得到了这个结果:
正如您所看到的,ListBox 中的项目大小不同,因为 DataContext
的属性名称不同。但我想获得类似尺寸的元素,如下所示:
你能帮我解答这个问题吗?预先感谢!
最佳答案
您应该使用网格列 SharedSizeGroup
属性 ( msdn )。
试试这个:
<ListBox Name="Lst" ItemsSource="{Binding Items}" HorizontalContentAlignment="Stretch"
Grid.IsSharedSizeScope="True">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" Width="500" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" BorderBrush="Black" >
<Grid >
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition SharedSizeGroup="A" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="Id" />
<Label Grid.Row="0" Grid.Column="1" Content="{Binding Id}" />
<Label Grid.Row="1" Grid.Column="0" Content="Name" />
<Label Grid.Row="1" Grid.Column="1" Content="{Binding Name}" />
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
关于c# - WPF 同步 ListBox 项目的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25339748/