如何在代码后面创建一个datatemplate? [英] How to create a datatemplate in code behind?

查看:68
本文介绍了如何在代码后面创建一个datatemplate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有xaml 

I have xaml 

<Control1 x:Name="something">

<&的DataTemplate GT;
< Ellipse Width =" 35"高度= QUOT 35 QUOT;填充= QUOT;红色">
< / Ellipse>
< / DataTemplate>< / Control1>

<DataTemplate> <Ellipse Width="35" Height="35" Fill="Red"> </Ellipse> </DataTemplate></Control1>


现在我想在代码中使用纯C#代码,怎么样?

Now I want to use pure C# code in code behind, how?

推荐答案

创建 在代码背后的模板中,您可以使用FrameworkElementFactory类。

To create  templates in code behind, you can use FrameworkElementFactory class.

但请参阅备注:

此类是不推荐的方式以编程方式创建模板,模板是FrameworkTemplate的子类,如ControlTemplate或DataTemplate;使用此类创建模板时,并非所有模板功能都可用。
以编程方式创建模板的推荐方法是使用XamlReader类的Load方法从字符串或内存流加载XAML。


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:// msdn。 microsoft.com/en-us/library/system.windows.frameworkelementfactory.aspx

https://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory.aspx

所以你可以试试这个。

public DataTemplate Create()
{
    StringReader stringReader = new StringReader(
    @"<DataTemplate 
xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
            <Ellipse Width="35" Height="35" Fill="Red">
            </Ellipse>
     </DataTemplate>");
    XmlReader xmlReader = XmlReader.Create(stringReader);
    return XamlReader.Load(xmlReader) as DataTemplate;
}

最好的问候,

Bob

Bob


这篇关于如何在代码后面创建一个datatemplate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆