不同的风格和切换主题

时间:2013-06-20 08:07:25

标签: c# windows-phone-7 xaml visual-studio-2012 windows-phone-8

好的,这是我的双重问题:

A)

开发时我需要能够从Dark转换为Light主题,而不必在模拟器中运行应用程序 - 这可能吗?如果是这样,怎么样?

B)

关于我的各种控件的颜色/等,我通常使用内置标准颜色(如Foreground="{StaticResource PhoneSubtleBrush}")。

现在,如果我想创建自定义样式并希望 - 让我们说 - 将Foreground设置为灰色(使用Light主题时),到 orangered (使用Dark主题时) - 应该怎么做?

1 个答案:

答案 0 :(得分:1)

A)可以在Visual Studio中使用设计器来查看页面在不同主题/重音组合下的外观。使用设备窗口(在“设计”菜单下)。 Blend中也存在类似的选项。

Visual Studio Device Window

B)您可以使用转换器执行此操作,但我喜欢为此类内容创建自己的资源。只需创建一个这样的类:

public class MyColorResource
{
    /// <summary>
    /// The resource name - as it can be referenced by within the app
    /// </summary>
    private const string ResourceName = "MyColorResource";

    /// <summary>
    /// Initializes a new instance of the <see cref="MyColorResource"/> class.
    /// </summary>
    public MyColorResource()
    {
        try
        {
            // This doesn't work in the designer - so don't even try
            if (DesignerProperties.IsInDesignTool)
            {
                return;
            }

            // Make sure we don't try and add the resource more than once - would happen if referenced on multiple pages or in app and page(s)
            if (!Application.Current.Resources.Contains(ResourceName))
            {
                if (Visibility.Visible == (Visibility)Application.Current.Resources["PhoneDarkThemeVisibility"])
                {
                    Application.Current.Resources.Add(ResourceName, new SolidColorBrush(Colors.Red));
                }
                else
                {
                    Application.Current.Resources.Add(ResourceName, new SolidColorBrush(Colors.Gray));
                }
            }
        }
        catch (Exception exc)
        {
            System.Diagnostics.Debug.WriteLine("Something went wrong - ask for your money back");
            System.Diagnostics.Debug.WriteLine(exc);
        }
    }
}

你应用程序的某个地方引用它(在App.xaml或你的主页通常是好的)

<phone:PhoneApplicationPage.Resources>
    <local:MyColorResource x:Key="AnythingAsNotActuallyUsed" />
</phone:PhoneApplicationPage.Resources>

然后您可以像在任何其他资源中一样在XAML中使用它:

<TextBlock Foreground="{StaticResource MyColorResource}" Text="{Binding Name}" />