使用FrameworkElementFactory的目的
本文关键字:FrameworkElementFactory 使用 | 更新日期: 2023-09-27 18:22:17
在我正在工作的一个应用程序中,我发现了以下代码-
public class MatrixCellTemplate : ColumnDataTemplate<MatrixCellContainer>
{
}
public class ColumnDataTemplate<T> : DataTemplate where T : FrameworkElement
{
public ColumnDataTemplate()
{
FrameworkElementFactory factory = new FrameworkElementFactory(typeof(T));
VisualTree = factory;
}
}
此MatrixCellTemplate
用于设置自定义DataGridTemplateColumn
(稍后添加到DataGrid.Columns
集合)的CellTemplate
,如下-
<DataGridTemplateColumn.CellTemplate>
<Matrix:MatrixCellTemplate />
</DataGridTemplateColumn.CellTemplate>
我不确定使用这个FrameworkElementFactory
有什么好处,如果我直接使用MatrixCellContainer
作为细胞模板-,我会面临什么问题
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Matrix:MatrixCellContainer>
</Matrix:MatrixCellContainer>
</DataTemplate>
<!--<Matrix:MatrixCellTemplate />-->
</DataGridTemplateColumn.CellTemplate>
很难猜测这段代码背后的原因,也许是为了减少XAML,但你真的可以手动定义它,从功能上来说,这并不重要(尤其是因为其中没有任何动态内容可以证明在代码背后做这件事是合理的)。
事实上,FrameworkElementFactory
无论如何都不推荐使用:
此类是一种不推荐使用的以编程方式创建模板的方法,模板是FrameworkTemplate的子类,如ControlTemplate或DataTemplate;使用此类创建模板时,并非所有模板功能都可用。以编程方式创建模板的推荐方法是使用XamlReader类的load方法从字符串或内存流加载XAML。