如何在代码中创建Silverlight数据模板?我已经看到了很多WPF的示例,但是对于Silverlight却没有。
编辑:这是基于以下圣地亚哥的答案,我现在正在使用的代码。
1 2 3 4 5 6 7 8 9
   | public DataTemplate Create(Type type) 
{ 
  return (DataTemplate)XamlReader.Load( 
          @"<DataTemplate 
            xmlns=""http://schemas.microsoft.com/client/2007""> 
            <" + type.Name + @" Text=""{Binding" + ShowColumn + @"}""/> 
            </DataTemplate>" 
   ); 
}  | 
 
这非常好用,可以让我随时更改绑定。 
尽管不能以编程方式创建它,但是可以从XAML字符串中以如下代码加载它:
1 2 3 4 5 6 7 8 9
   |     public static DataTemplate Create(Type type) 
    { 
        return (DataTemplate) XamlReader.Load( 
            @"<DataTemplate 
                xmlns=""http://schemas.microsoft.com/client/2007""> 
                <" + type.Name + @"/> 
              </DataTemplate>" 
          ); 
    }  | 
 
上面的代码段创建了一个包含单个控件的数据模板,该控件可能是具有所需内容的用户控件。
我在这段代码中遇到了一些问题,使元素没有出现异常。仅供参考,这是我需要在DataTemplate ... 
中包含我的命名空间。
1 2 3 4 5 6 7 8
   | private DataTemplate Create(Type type) 
        { 
            string xaml = @"<DataTemplate  
                xmlns=""http://schemas.microsoft.com/client/2007"" 
                xmlns:controls=""clr-namespace:" + type.Namespace + @";assembly=" + type.Namespace + @"""> 
                <controls:" + type.Name + @"/></DataTemplate>"; 
            return (DataTemplate)XamlReader.Load(xaml); 
        }  | 
 
 
是的,Silverligt 4比WPF的当前版本早。
当您将模板添加为资源时,即像我一样
我在ResourceDictionary之间的Application.xaml MergedResources中添加了一个userControl模板。
在XAML中,如果标记实现了IDictionary,则可以使用x:Key属性。像这样
1 2 3 4 5
   |    <ResourceDictionary> 
    <DataTemplate x:Key="TextBoxEditTemplate"> 
    <Some user control x:Name="myOwnControl" /> 
    </DataTemplate> 
   </ResourceDictionary>  | 
 
好!您可以通过编码Application.Current.resources [" TextBoxEditTemplate"]来访问模板
另一方面,用于查找此模板成员的某些方法将不起作用。在此DataTemplate旁边没有实现IDictionary,因此您不能为此dataTemplate中的项目分配x:Key属性。作为示例中的myOwnControl。
在没有xaml的情况下,当前的Silverlight在创建完全动态代码隐藏的DataTemplates方面有一些限制。即使在WPF上也可以使用。
无论如何,到目前为止最好的解决方案是为datatemplate创建XAML脚本,您可以在DataTemplate脚本中添加一些values元素。我们创建了自己的usercontrols,它具有DependencyObjectProperty ... 
的某些属性。
最后,如果您的对象没有继承,即不是MyControl:UserControl,您可以通过这种方式继承MyObject:DependencyObject,这样您就可以通过调用Application.Current.Resources.FirstChilderen ... 
 FindName仅在WPF中起作用
来自MSDN的引用:
The XAML usage that defines the content for creating a data template is not exposed as a settable property. It is special behavior built into the XAML processing of a DataTemplate object element.