WPF DataTemplate的后端用法(动态生成控件)
定义控件可以使用FrameworkElementFactory
,也可以使用XmlReader
FrameworkElementFactory的用法
为DataGrid添加一列,列的每个单元格包含修改、删除两个按钮
DataGridTemplateColumn dataGridTemplateColumn = new DataGridTemplateColumn();
dataGridTemplateColumn.Header = "操作";
dataGridTemplateColumn.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
//Grid分列
FrameworkElementFactory gridFactory = new FrameworkElementFactory(typeof(Grid));
FrameworkElementFactory col1 = new FrameworkElementFactory(typeof(ColumnDefinition));
FrameworkElementFactory col2 = new FrameworkElementFactory(typeof(ColumnDefinition));
col1.SetValue(ColumnDefinition.WidthProperty, new GridLength(1, GridUnitType.Star));
col2.SetValue(ColumnDefinition.WidthProperty, new GridLength(1, GridUnitType.Star));
gridFactory.AppendChild(col1);
gridFactory.AppendChild(col2);
//添加两个Button
FrameworkElementFactory btn1Factory = new FrameworkElementFactory(typeof(Button));
btn1Factory.SetValue(Button.ContentProperty, "修改");
//添加事件
//https://stackoverflow.com/questions/47401286/how-to-pro-gramatically-add-click-event-to-frameworkelementfactory
btn1Factory.AddHandler(Button.ClickEvent, new RoutedEventHandler(ModifyData_Click));
FrameworkElementFactory btn2Factory = new FrameworkElementFactory(typeof(Button));
btn2Factory.SetValue(Button.ContentProperty, "删除");
btn2Factory.AddHandler(Button.ClickEvent, new RoutedEventHandler(DeleteData_Click));
btn2Factory.SetValue(Grid.ColumnProperty, 1);
gridFactory.AppendChild(btn1Factory);
gridFactory.AppendChild(btn2Factory);
//关键代码
System.Windows.DataTemplate cellTemplate1 = new System.Windows.DataTemplate();
cellTemplate1.VisualTree = gridFactory;
dataGridTemplateColumn.CellTemplate = cellTemplate1;
dataGrid1.Columns.Add(dataGridTemplateColumn);
关于样式的问题,在xaml中写的样式一样适用,也可以在后端通过.Style
绑定样式
XmlReader的用法
var dataTemplateString =
@" <DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<StackPanel Orientation=""Horizontal"">
<Button Content=""修改"" x:Name=""mButton""></Button>
<Button Content=""删除""></Button>
</StackPanel>
</DataTemplate>";
var stringReader = new StringReader(dataTemplateString);
XmlReader xmlReader = XmlReader.Create(stringReader);
System.Windows.DataTemplate dataTemplate = (System.Windows.DataTemplate)XamlReader.Load(xmlReader);
DataGridTemplateColumn col1 = new DataGridTemplateColumn();
col1.CellTemplate = dataTemplate;
dataGrid2.Columns.Add(col1);
示例代码
参考资料
What is the code behind for datagridtemplatecolumn, and how to use it?
Create a grid in WPF with a FrameworkElementFactory
How generate custom columns for FrameworkElementFactory(typeof(Datagrid))?
XamlReader with Click Event
学习技术最好的文档就是【官方文档】,没有之一。
还有学习资料【Microsoft Learn】、【CSharp Learn】、【My Note】。
如果,你认为阅读这篇博客让你有些收获,不妨点击一下右下角的【推荐】按钮。
如果,你希望更容易地发现我的新博客,不妨点击一下【关注】。