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);

示例代码

DataTemplateByCodeDemoWindow

参考资料

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

posted @ 2020-06-05 17:43  Lulus  阅读(3464)  评论(1编辑  收藏  举报