我可以将DataGrid的CellTemplate定义为资源,以便可以在多个列中重复使用?

编程入门 行业动态 更新时间:2024-10-23 17:24:13
本文介绍了我可以将DataGrid的CellTemplate定义为资源,以便可以在多个列中重复使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我想要一个特定的模板,用于DataGrid中的所有列。通常的方法是我将在DataGrid中的每个列复制多个DataTemplate的整个XAML。

有没有办法我可以将CellTemplate定义为全局资源,然后将绑定的路径属性传递给它,以便它从DataContext显示正确的项目?

这是可能吗? p>

解决方案

使用键/名在App.Xaml文件中创建DataTemplate。

< DataTemplate x:Name =myTemplateTargetType =sdk:DataGridTemplateColumn> < StackPanel Orientation =Horizo​​ntal> < TextBox Text ={Binding FirstName}BorderThickness =0/> < TextBox Text ={Binding LastName}BorderThickness =0/> < / StackPanel> < / DataTemplate>

现在您可以在DataGrid中使用此模板,如

< sdk:DataGridTemplateColumn Header =NameCellTemplate = {StaticResource myTemplate}>

或 您可以将代码中的Binding Path名称传递给... 。

string colPath =FirstName; DataGrid grid = new DataGrid(); grid.ItemsSource = myViewModel.EmpCollection; DataGridTemplateColumn column = new DataGridTemplateColumn(); DataTemplate itemTemplate =(DataTemplate)XamlReader.Load(< DataTemplate xmlns = \schemas.microsoft/client/2007\>< ContentPresenter Content = \{ Binding Path =+ colPath +} \/>< / DataTemplate>); column.CellTemplate = itemTemplate; grid.Columns [0] =列;

希望这将有所帮助。

I want a specific template for all my columns in DataGrid. The usual method is I will replicate the entire XAML for DataTemplate multiple times in the DataGrid in each of the Column.

Is there any way I can define the CellTemplate globally as a resource and then just pass the the "Path" property of "Binding" to it, so that it displays the correct item from the DataContext ?

Is this possible ?

解决方案

Create DataTemplate in App.Xaml file with key/name.

<DataTemplate x:Name="myTemplate" TargetType="sdk:DataGridTemplateColumn"> <StackPanel Orientation="Horizontal"> <TextBox Text="{Binding FirstName}" BorderThickness="0"/> <TextBox Text="{Binding LastName}" BorderThickness="0"/> </StackPanel> </DataTemplate>

Now you can use this template in DataGrid like

<sdk:DataGridTemplateColumn Header="Name" CellTemplate={StaticResource myTemplate}>

OR You can to pass Binding Path name in code behind like...

string colPath = "FirstName"; DataGrid grid = new DataGrid(); grid.ItemsSource = myViewModel.EmpCollection; DataGridTemplateColumn column = new DataGridTemplateColumn(); DataTemplate itemTemplate = (DataTemplate)XamlReader.Load("<DataTemplate xmlns=\"schemas.microsoft/client/2007\"> <ContentPresenter Content=\"{Binding Path=" + colPath + "}\" /></DataTemplate>"); column.CellTemplate = itemTemplate; grid.Columns[0] = column;

Hope this will help.

更多推荐

我可以将DataGrid的CellTemplate定义为资源,以便可以在多个列中重复使用?

本文发布于:2023-11-16 22:04:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607651.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   重复使用   定义   资源   DataGrid

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!