[英]Custom Headers in WPF DataGrid
我有以下数据 model:
public class ListData
{
public string Name { get; init; }
public IEnumerable<string> Items { get; init; }
public bool IsSelected { get; set; }
}
我为视图 DataContext 设置了一个 ViewModel,它具有一个公共ObservableCollection<ListData>
属性,也称为 ListData。
我希望能够将Name
属性作为 DataGrid 控件中的列 header,并将Items
元素作为列中的行。
到目前为止我有这个:
<DataGrid ItemsSource="{Binding ListData}"
Grid.Row="2"
Grid.Column="2">
<DataGrid.Columns>
<DataGridTextColumn Header="{Binding Name}" Binding="{Binding Items}"/>
</DataGrid.Columns>
</DataGrid>
但是,这仅显示以下内容:结果
我究竟做错了什么?
理想情况下,这就是我想要的示例:目标
WPF 中的每个组件或控件都是出于独特的原因而完成的。 因此,DataGrid 有一个特定的模板来实现一个特定的目标或责任。 如果您需要更改结果的结构,则必须更改 DataGrid 的模板,这不是正确的方法。 当您尝试进行此类自定义时,我建议您使用基本且简单的控件,这将使您轻松实现目标。 这是您的几行示例,使用 ItemsControl 和 ListBox。
<Window x:Class="DataGridCustomHeader.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<ItemsControl ItemsSource="{Binding ListData}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding Name}" BorderThickness="1" BorderBrush="Black"/>
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Window>
使用仅用于测试的代码(您可以使用视图模型)
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
namespace DataGridCustomHeader
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<ListData> ListData { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
ListData = new ObservableCollection<ListData>
{
new ListData
{
Name="Letters",
Items = new List<string>{"A", "B", "C"}
},
new ListData
{
Name="Words",
Items = new List<string>{"Hello", "Word", ""}
},
new ListData
{
Name="Numbers",
Items = new List<string>{"1", "2", "3"}
}
};
}
}
}
using System.Collections.Generic;
namespace DataGridCustomHeader
{
public class ListData
{
public string Name { get; set; }
public IEnumerable<string> Items { get; set; }
public bool IsSelected { get; set; }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.