DataGrid动态增加列
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel Orientation="Horizontal"> <Button Content="Add Column" Click="AddColumn_Click" Margin="5"/> <Button Content="Add Data" Click="AddData_Click" Margin="5"/> </StackPanel> <DataGrid x:Name="dataGrid" AutoGenerateColumns="True" Grid.Row="1"/> </Grid> </Window>
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Dynamic; using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace WpfApplication1 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { ObservableCollection<ExpandoObject> items = new ObservableCollection<ExpandoObject>(); public MainWindow() { InitializeComponent(); for (int i = 0; i < 5; i++) { dynamic item = new ExpandoObject(); item.A = "Property A value - " + i.ToString(); item.B = "Property B value - " + i.ToString(); items.Add(item); } dataGrid.Columns.Add(new DataGridTextColumn() { Header = "A", Binding = new Binding("A") }); dataGrid.Columns.Add(new DataGridTextColumn() { Header = "B", Binding = new Binding("B") }); dataGrid.ItemsSource = items; } private void AddData_Click(object sender, RoutedEventArgs e) { dynamic item = new ExpandoObject(); item.A = "New Item - A"; item.B = "New Item - B"; items.Add(item); } int newColumnIndex = 1; private void AddColumn_Click(object sender, RoutedEventArgs e) { foreach (IDictionary<String, Object> item in items) { item.Add("NewColumn" + newColumnIndex, "New Column Value - " + newColumnIndex.ToString()); } dataGrid.Columns.Add(new DataGridTextColumn() { Header = "New Column" + newColumnIndex, Binding = new Binding("NewColumn" + newColumnIndex) }); newColumnIndex++; } } }
https://social.microsoft.com/Forums/zh-CN/69ac1292-9512-4bd3-b691-795f64cb0aa0/wpf-datagrid-?forum=wpfzhchs
时间: 2024-10-07 06:47:54