我想要 DataGrid 中所有列的特定模板。通常的方法是我将在每个列的 DataGrid 中多次复制 DataTemplate 的整个 XAML。
有什么方法可以将 CellTemplate 全局定义为资源,然后将“Binding”的“Path”属性传递给它,以便它显示 DataContext 中的正确项目?
这可能吗 ?
我想要 DataGrid 中所有列的特定模板。通常的方法是我将在每个列的 DataGrid 中多次复制 DataTemplate 的整个 XAML。
有什么方法可以将 CellTemplate 全局定义为资源,然后将“Binding”的“Path”属性传递给它,以便它显示 DataContext 中的正确项目?
这可能吗 ?
使用键/名称在 App.Xaml 文件中创建 DataTemplate。
<DataTemplate x:Name="myTemplate" TargetType="sdk:DataGridTemplateColumn">
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding FirstName}" BorderThickness="0"/>
<TextBox Text="{Binding LastName}" BorderThickness="0"/>
</StackPanel>
</DataTemplate>
现在您可以在 DataGrid 中使用此模板,例如
<sdk:DataGridTemplateColumn Header="Name" CellTemplate={StaticResource myTemplate}>
或者
您可以在代码后面传递绑定路径名称,例如...
string colPath = "FirstName";
DataGrid grid = new DataGrid();
grid.ItemsSource = myViewModel.EmpCollection;
DataGridTemplateColumn column = new DataGridTemplateColumn();
DataTemplate itemTemplate = (DataTemplate)XamlReader.Load("<DataTemplate xmlns=\"http://schemas.microsoft.com/client/2007\"> <ContentPresenter Content=\"{Binding Path=" + colPath + "}\" /></DataTemplate>");
column.CellTemplate = itemTemplate;
grid.Columns[0] = column;
希望这会有所帮助。