Silverlight基于对象属性值更改样式(即DataTrigger)

12 silverlight triggers coding-style

有没有人有一个成功的解决方法,可以根据底层数据对象的属性更改silverlight中的样式,因为当值发生变化时,样式也会发生变化.我简单地使用了WPF,它显然有DataTrigger似乎涵盖了这一点,但它在Silverlight中缺失.

我发现了这个:http: //blois.us/blog/2009/04/datatrigger-bindings-on-non.html

但它似乎不适用于造型..

谢谢你的时间

Sor*_*oot 10

Silverlight不包含DataTemplateSelector,它用于根据数据绑定元素和数据对象选择数据模板.但是,建立自己的并不难.

从继承自System.Windows.Controls.ContentControl的类开始.此类具有数据模板的属性和内容的属性,您可以使用它绑定到该属性.像这样在OnContentChanged方法上创建一个覆盖

protected override void OnContentChanged(object oldContent, object newContent) 
{
}
Run Code Online (Sandbox Code Playgroud)

我更喜欢将模板放在单独的字典中,以防万一我需要在项目之间共享它们.在此方法中,将此控件的模板设置为从字典中挑选的模板.就像是:

Switch(DataStatus){
  case 0: ContentTemplate = LoadFromDictionary(
                                "DataTemplateDemo;component/DataTemplates.xaml",
                                "Status0Template");
          break;
  case 1: ContentTemplate = LoadFromDictionary(
                                "DataTemplateDemo;component/DataTemplates.xaml", 
                                "Status1Template");
          break;
   //etc      
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,应该是一个带有几个数据模板的字典名称DataTemplates.xaml.

在xaml文件中,使用模板选择器类作为列表的模板:

 <ListBox x:Name="AnInterrestingList">
    <ListBox.ItemTemplate>
    <DataTemplate>
        <DataTemplateDemo:DateTemplateSelector Content="{Binding}"/>
    </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

我使用下面的帮助方法从字典中检索模板:

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;
}
Run Code Online (Sandbox Code Playgroud)

更新

与此同时,我写了一篇博文,里面有关于这个主题的示例代码.它可以在我的博客上找到.