C# 如何在Silverlight中使用动态ResourceDictionary源?
如何在Silverlight中使用动态ResourceDictionary源?我的应用程序有一个“Styles.xaml”,其中包含许多样式定义,并引用了一个“Colors.xaml”,其中定义了两个笔刷: Styles.xaml:C# 如何在Silverlight中使用动态ResourceDictionary源?,c#,silverlight,C#,Silverlight,如何在Silverlight中使用动态ResourceDictionary源?我的应用程序有一个“Styles.xaml”,其中包含许多样式定义,并引用了一个“Colors.xaml”,其中定义了两个笔刷: Styles.xaml: <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/Project;component/Colo
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Project;component/Colors.xaml" />
</ResourceDictionary.MergedDictionaries>
<DataTemplate x:Key="MyLayoutTemplate">
<Button Background="ButtonBackgroundBrush">Button Title</Button>
</DataTemplate>
<!-- A lot of other definitions -->
</ResourceDictionary>
按钮标题
Colors.xaml:
<ResourceDictionary>
<SolidColorBrush x:Key="ButtonBackgroundBrush" Color="#FFFFFFFF"/>
<!-- ... -->
</ResourceDictionary>
基本上,style.xaml定义了布局和颜色。xaml定义了颜色(duh)。My App.xaml仅引用此Styles.xaml
我需要的是一种不使用此选项的方法:
<ResourceDictionary Source="/Project;component/Colors.xaml" />
并将该源属性“指向”(或绑定)到一个静态类,在该静态类中将动态定义该属性。大概是这样的:
<ResourceDictionary Source="{Binding Settings.ThemeUri}" />
有什么方法可以实现这一点吗?您可以仅在XAML中实现这一点,但用代码创建字典很简单
ResourceDictionary styleDictionary = new ResourceDictionary()
{
Source = new Uri("/Project;component/Styles.xaml", UriKind.Absolute)
};
ResourceDictionary colorDictionary = new ResourceDictionary()
{
Source = new Uri("/Project;component/Colors.xaml", UriKind.Absolute)
};
styleDictionary.MergedDictionaries.Add(colorDictionary);
Application.Current.Resources.MergedDictionaries.Add(styleDictionary);
谢谢你的回答,但是没有用。看看里面的style.xaml引用了Colors.xaml,我想这只是因为我在示例中混淆了URI。现在已修复。再次感谢,但仍然无法使用。我希望能够在运行时选择颜色方案,选择除Colors.xaml以外的xaml。问题是style.xaml对Colors.xaml有这种硬引用。资源字典应该完全在代码中定义,这样您就可以根据自定义逻辑设置URI——我的示例中的硬编码URI只是一个示例。