我们需要解决以下问题。 在视图中我们定义了包含TextBox的DataGrid和DataTemplate。 DataTemplate用于DataGrid列的HeaderTemplate。 DataGrid的列是从代码动态添加的(不在View后面的代码中)。
我的问题是:
我想在ViewModel中填写Dictionary。该词典将包含Keys = DataGridTextColumn.Header(列名称)和Values = TextBox.Text,并且应该在TextBox中的文本更改时不断填充。 怎么做?
这是我的代码:
MainWindow.xaml
<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"
xmlns:wpfToolkit="http://schemas.microsoft.com/wpf/2008/toolkit">
<Window.Resources>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</Window.Resources>
<Grid>
<DataGrid AutoGenerateColumns="False" HeadersVisibility="Column" HorizontalAlignment="Left" VerticalAlignment="Top" Loaded="Grid_Loaded">
<DataGrid.Resources>
<DataTemplate x:Key="HeaderDataTemplate">
<StackPanel Orientation="Vertical" >
<ContentControl Content="{Binding}" />
<TextBox x:Name="tbName"/>
</StackPanel>
</DataTemplate>
</DataGrid.Resources>
<DataGrid.Columns>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
DataGrid grid = (DataGrid)sender;
ResourceDictionary resourecs = grid.Resources;
grid.Columns.Add(new DataGridTextColumn() { Header = "Column_1", Width = 150, HeaderTemplate = (DataTemplate)resourecs["HeaderDataTemplate"] });
grid.Columns.Add(new DataGridTextColumn() { Header = "Column_2", Width = 150, HeaderTemplate = (DataTemplate)resourecs["HeaderDataTemplate"] });
grid.Columns.Add(new DataGridTextColumn() { Header = "Column_N", Width = 150, HeaderTemplate = (DataTemplate)resourecs["HeaderDataTemplate"] });
}
}
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public IDictionary<string, string> HeaderTextValues
{
//Here is Dictionary, which should by filled by Key = DataGridTextColumn.Header, Value = TextBox.Text
get { return null; /*???? */ }
}
}
}