在我正在工作的应用程序之一中,我找到了这段代码 -
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
的CellTemplate
(稍后添加到DataGrid.Columns
)集合)像这样 -
<DataGridTemplateColumn.CellTemplate>
<Matrix:MatrixCellTemplate />
</DataGridTemplateColumn.CellTemplate>
我不确定使用此 FrameworkElementFactory
有什么好处,以及如果直接使用 MatrixCellContainer
作为单元格模板会遇到什么问题 -
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Matrix:MatrixCellContainer>
</Matrix:MatrixCellContainer>
</DataTemplate>
<!--<Matrix:MatrixCellTemplate />-->
</DataGridTemplateColumn.CellTemplate>
最佳答案
很难猜测这段代码背后的原因,也许是为了减少 XAML,但您实际上最好手动定义它,从功能上来说这并不重要(特别是因为其中没有任何动态内容可以证明在代码中这样做是合理的-排在第一位)。
事实上FrameworkElementFactory
无论如何已被弃用:
This class is a deprecated way to programmatically create templates, which are subclasses of FrameworkTemplate such as ControlTemplate or DataTemplate; not all of the template functionality is available when you create a template using this class. The recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class.
关于c# - 使用FrameworkElementFactory的目的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9091853/