Rik*_*kki 4 c# data-binding wpf xaml
如何通过使用 WPF 或创建自定义控件来获得以下视图?
由于我需要使用数据模板并且单元格值可能是对象实例,因此我无法使用 WinForms 来使用旧结构。(更不用说即使我可以我也不会!)
分组级别可以是一个(如图所示)或多个。四个步骤在这里是令人满意的。
任何其他解决方案将不胜感激。
干得好
我定义了一个绑定到 Items(您的数据)的 ItemsControl 并定义了一个组样式以按照您的期望显示数据。
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Border BorderBrush="Black" BorderThickness=".5" Padding="4">
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" />
</Border>
<ItemsPresenter Grid.Column="1" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ItemsControl.GroupStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness=".5" Padding="4">
<TextBlock Text="{Binding Data}" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
这是准备组的代码
Items = new ObservableCollection<Item>();
Items.Add(new Item() { Key = "abcd", Data = 1 });
Items.Add(new Item() { Key = "abcd", Data = 2 });
Items.Add(new Item() { Key = "qwer", Data = 1 });
Items.Add(new Item() { Key = "qwer", Data = 2 });
CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(Items);
PropertyGroupDescription groupDescription = new PropertyGroupDescription("Key");
view.GroupDescriptions.Add(groupDescription);
Run Code Online (Sandbox Code Playgroud)
在此之后,将一切交给 WPF 并享受造型和绑定的力量
多级分组
要实现多级分组,您只需将 PropertyGroupDescription 添加到 view.GroupDescriptions
例如
groupDescription = new PropertyGroupDescription("Key2");
view.GroupDescriptions.Add(groupDescription);
Run Code Online (Sandbox Code Playgroud)

您可以创建的子组没有限制,您只需要一个组键即可。
| 归档时间: |
|
| 查看次数: |
7291 次 |
| 最近记录: |