我在WPF中使用了itemscontrol,我将字典集合作为itemscontrol的itemsource。在此字典集合中,将使用key和observablecollection。每个字典项目的可观察集合中将包含不同的项目。因此,当我获得一个itemsource时,它将采用相同的高度。
查看代码:
<ItemsControl
Grid.Row="1"
Height="Auto"
ItemsSource="{Binding Values}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
IsItemsHost="True"
Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<GroupBox
MinWidth="303"
Margin="5,0,0,0">
<ItemsControl Margin="20,5,0,5">
<ItemsControl.Resources>
<CollectionViewSource x:Key="Collection" Source="{Binding Value}" />
<DataTemplate DataType="{x:Type Model:Sensor}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label
Grid.Column="1"
Content="{Binding Name}"
FontFamily="SegoeUI-Semibold"
FontSize="12"
FontWeight="SemiBold" />
<Label
Grid.Column="2"
HorizontalContentAlignment="Center"
Content="{Binding Value}"
FontFamily="SegoeUI"
FontSize="12" />
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type Model:DigitalInput}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label
Grid.Column="1"
Content="{Binding Name}"
FontFamily="SegoeUI-Semibold"
FontSize="12"
FontWeight="SemiBold" />
<Label
Grid.Column="2"
HorizontalContentAlignment="Center"
Content="{Binding InputState}"
FontFamily="SegoeUI"
FontSize="12" />
</Grid>
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding Source={StaticResource Collection}}" />
</CompositeCollection>
</ItemsControl.ItemsSource>
</ItemsControl>
</GroupBox>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
查看课程代码:
private Dictionary<string, ObservableCollection<IValue>> values;
public Dictionary<string, ObservableCollection<IValue>> Values
{
get { return values; }
set { values = value; }
}
答案 0 :(得分:2)
这是WrapPanel的工作方式。如果设置为“水平”,则行中的所有项目都将具有相同的高度,并将元素包装到下一行。 您可以尝试为WrapPanel指定Orientation =“ Vertical” ,但不确定是否适合您。在这种情况下,列中的所有元素都将具有相同的宽度。
否则,您不需要WrapPanel或UniformGrid,您需要使用另一个名为StaggeredPanel的面板。 uwp的Source code可以在WPF中轻松使用,我刚刚检查了一下。
只需重写一行,对以下answer来说没什么大不了的:RegisterPropertyChangedCallback(Panel.HorizontalAlignmentProperty, OnHorizontalAlignmentChanged);
可以在codeproject(称为VariableSizedWrapGrid)上找到类似控件的说明。但是我检查了它,发现它在某处有错误。
在ios上,它被称为镶嵌视图或Android上用于RecyclerView的StaggeredLayoutManager。
答案 1 :(得分:0)
尝试使用WrapPanel
代替UniformGrid
:
<UniformGrid Columns="1" IsItemsHost="True" />
此外,我不确定Height="Auto"
的设置。去掉它。该设置属于网格的RowDefinition
。