【问题标题】:Windows Phone: how to change the Application style programmaticallyWindows Phone:如何以编程方式更改应用程序样式
【发布时间】: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


【解决方案1】:

您可以尝试使用此处描述的方法 Jeff Wilcox:http://www.jeff.wilcox.name/2012/01/phonethememanager/

此处描述了 Silverlight 的替代方法,我不确定这是否适用于 Windows Phone(尽管它们共享一些代码库): http://silverlightips.wordpress.com/2010/04/29/change-themestyle-using-merged-dictionaries/

如果你有一个大型应用程序,这两种方法都不容易,你可以考虑另一种选择,比如(叫我疯了)

<Button Style="{Binding Locator.Theme, Converter={StaticResource StyleThemeConverter}, ConverterParameter=RefreshButtonStyle}"

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多