Purpose of using FrameworkElementFactory

荒凉一梦 提交于 2019-11-28 08:28:51

问题


In one of the application I am working I have found this code -

public class MatrixCellTemplate : ColumnDataTemplate<MatrixCellContainer>
{
}

public class ColumnDataTemplate<T> : DataTemplate where T : FrameworkElement
{
    public ColumnDataTemplate()
    {
        FrameworkElementFactory factory = new FrameworkElementFactory(typeof(T));
        VisualTree = factory;
    }
}

This MatrixCellTemplate is used to set the CellTemplate of a custom DataGridTemplateColumn (later added to DataGrid.Columns collection) like this -

<DataGridTemplateColumn.CellTemplate>
    <Matrix:MatrixCellTemplate />
</DataGridTemplateColumn.CellTemplate>

I am not sure what is the benefit of using this FrameworkElementFactory and what problem I can face if I directly use MatrixCellContainer as cell template -

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <Matrix:MatrixCellContainer>
        </Matrix:MatrixCellContainer>
    </DataTemplate>
    <!--<Matrix:MatrixCellTemplate />-->
</DataGridTemplateColumn.CellTemplate>

回答1:


Hard to guess the reasoning behind this code, maybe to reduce the XAML, but you really might as well define it manually, functionally it does not matter (especially since there is nothing dynamic in there that would justify doing it in code-behind in the first place).

In fact FrameworkElementFactory is deprecated anyway:

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.



来源:https://stackoverflow.com/questions/9091853/purpose-of-using-frameworkelementfactory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!