在代码中创建 Silverlight DataTemplate [英] Creating a Silverlight DataTemplate in code

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

问题描述

如何在代码中创建 Silverlight 数据模板?我看过很多 WPF 的例子,但 Silverlight 没有.

How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight.

根据下面圣地亚哥的回答,这是我现在使用的代码.

Here's the code I'm now using this for, based on the answer from Santiago below.

public DataTemplate Create(Type type)
{
  return (DataTemplate)XamlReader.Load(
          @"<DataTemplate
            xmlns=""http://schemas.microsoft.com/client/2007"">
            <" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/>
            </DataTemplate>"
   );
}

这非常有效,并且允许我即时更改绑定.

This works really nicely and allows me to change the binding on the fly.

推荐答案

虽然您无法以编程方式创建它,但您可以使用以下代码从 XAML 字符串加载它:

Although you cannot programatically create it, you can load it from a XAML string in code like this:

    public static DataTemplate Create(Type type)
    {
        return (DataTemplate) XamlReader.Load(
            @"<DataTemplate
                xmlns=""http://schemas.microsoft.com/client/2007"">
                <" + type.Name + @"/>
              </DataTemplate>"
          );
    }

上面的代码段创建了一个包含单个控件的数据模板,该控件可能是一个包含您需要的内容的用户控件.

The snippet above creates a data template containing a single control, which may be a user control with the contents you need.

这篇关于在代码中创建 Silverlight DataTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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