Silverlight 不包含DataTemplateSelector,它用于根据数据绑定元素和数据对象选择数据模板。但是,建立自己的并不难。
从继承自 System.Windows.Controls.ContentControl 的类开始。此类具有数据模板的属性和内容的属性,您可以使用它们进行绑定。像这样在OnContentChanged 方法上创建一个覆盖
protected override void OnContentChanged(object oldContent, object newContent)
{
}
我更喜欢将模板放在单独的字典中,以防我需要在项目之间共享它们。
在此方法中,将此控件的模板设置为从字典中选取的模板。比如:
Switch(DataStatus){
case 0: ContentTemplate = LoadFromDictionary(
"DataTemplateDemo;component/DataTemplates.xaml",
"Status0Template");
break;
case 1: ContentTemplate = LoadFromDictionary(
"DataTemplateDemo;component/DataTemplates.xaml",
"Status1Template");
break;
//etc
}
在这种情况下,应该是带有几个数据模板的字典名称 DataTemplates.xaml。
在您的 xaml 文件中,使用模板选择器类作为列表的模板:
<ListBox x:Name="AnInterrestingList">
<ListBox.ItemTemplate>
<DataTemplate>
<DataTemplateDemo:DateTemplateSelector Content="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我使用如下的辅助方法从字典中检索模板:
public static DataTemplate LoadFromDictionary(string dictionary,
string template)
{
var doc = XDocument.Load(dictionary);
var dict = (ResourceDictionary)XamlReader
.Load(doc.ToString(SaveOptions.None));
return dict[template] as DataTemplate;
}
更新
与此同时,我写了一篇博文,其中包含有关此主题的示例代码。它可以在my blog 上找到。