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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM