[英]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.