【发布时间】:2013-02-28 10:24:38
【问题描述】:
在我的 Windows Phone 8 应用程序中,我在 /Styles/DefaultStyles.xaml
位置的 xaml 文件中定义了一些隐式样式我有一个类似的文件,但具有不同的颜色、字体等...在 /Styles/GreenStyles.xaml 中定义。
我在我的 App.xaml 中引用了默认样式文件,如下所示:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles/DefaultStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
我想让我的应用程序以编程方式从其他样式文件 (GreenStyles) 切换其隐式样式。
我怎样才能做到这一点?
**
更新:
我设法将资源字典的来源更改如下:
ResourceDictionary style = App.Current.Resources.MergedDictionaries.ToList()[0];
string source = String.Format("/ApplicationName;component/Styles/GreenStyles.xaml");
style.Source = new Uri(source, UriKind.Relative);
注意:组件这个词一定要这样写,以免出现异常
现在我有一个问题: 只有 隐式样式(那些没有 x:Key 属性的样式)在字典源发生变化时切换。
具有指定键并在两个文件中定义两次(具有不同属性)的任何其他样式将不会反映在 UI 中。
所以如果我有这些文件: DefaultStyles.xaml:
<Style x:Key="MainGrid" TargetType="Grid">
<Setter Property="Background" Value="Red"/>
</Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="Red"/>
<Setter Property="FontSize" Value="24"/>
</Style>
</ResourceDictionary>
还有: GreenStyles.xaml:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone">
<Style x:Key="MainGrid" TargetType="Grid">
<Setter Property="Background" Value="Green"/>
</Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="Green"/>
<Setter Property="FontSize" Value="24"/>
</Style>
</ResourceDictionary>
并且我将源切换为指向 GreenStyles.xaml,任何具有 MainGrid 样式的网格仍会将其背景设为 Red。
这可能是什么原因?
【问题讨论】:
-
您能否给您的
ResourceDictionary一个x:Name值,然后在您的代码隐藏中引用它以在需要时更改Source属性? -
我这样做了,主题变了,但是有问题,请检查问题中的更新
-
嗯.. 这有帮助吗? stackoverflow.com/questions/2032294/… - 我从来没有完全这样做过,但似乎它可能会有所帮助。
标签: xaml windows-phone-8 windows-phone