【发布时间】:2015-10-27 09:25:17
【问题描述】:
我正在使用 wpf,我遇到的问题是我想将一个集合绑定到一个元素,该元素会根据窗口大小调整其内容的大小。
为了更清楚,举个小例子: 对于静态行为,我会做类似的事情。
<Grid Margin="10,10,10,10">
<Grid.RowDefinitions>
<RowDefinition Height="50*"/>
<RowDefinition Height="50*"/>
<RowDefinition Height="50*"/>
<RowDefinition Height="50*"/>
</Grid.RowDefinitions>
<Button Grid.Row="0"></Button>
<Button Grid.Row="1"></Button>
<Button Grid.Row="2"></Button>
<Button Grid.Row="3"></Button>
</Grid>
在这种情况下,所有 Button 都会随窗口增大/缩小。
但现在我想让它更有活力。 我有一个 ObservableCollection,其中包含要添加的所有元素(动态量)。 对于第一个实现,我将所有元素添加到 StackPanel。但是 StackPanel 中的控件会调整大小,因此我考虑改用网格。
实际解决方案:
<Window.Resources>
<DataTemplate DataType="{x:Type local:OwnObject}">
<Button DataContext="{Binding}" Content="{Binding Text}" Margin="0,0,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding SubItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel x:Name="stackPanel" Margin="0,0,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
如何使用 ItemsControl 为每个元素生成一行并将其添加到该行?也欢迎其他解决问题的方法。
【问题讨论】:
标签: c# wpf data-binding grid itemscontrol