【问题标题】:UWP, is it possible to add ResourceDictionary value programmatically?UWP,是否可以通过编程方式添加 ResourceDictionary 值?
【发布时间】:2021-07-31 13:09:34
【问题描述】:

我正在为我的应用添加复杂的主题。我的想法是当用户更改主题时,我会加载一个 ResourceDictionary 并在运行时更改它的子项。 但是插入操作总是失败,请帮帮我。

以下是我所做的:

auto newResourceDic = ref new ResourceDictionary();
newResourceDic->Source = ref new Uri("ms-appx:///XAMLPages/test.xaml");
if (newResourceDic->HasKey(L"TitleBarColor"))
{
    newResourceDic->Remove(L"TitleBarColor");  
    //It's a SolidColorBrush, I want to replace this brush to a more complex bitmapbrush
    //For convenience, I use a solidcolorbrush instead
    Windows::UI::Color c;
    c.A = 255;
    c.R = 255;
    c.G = 0;
    c.B = 0;
    testbrush = ref new Windows::UI::Xaml::Media::SolidColorBrush(c);

    //HRESULT:0x800F1000 No installed components were detected.
    //WinRT information: Local values are not allowed in resource dictionary with Source set [Line: 0 Position: 0]
    newResourceDic->Insert("TitleBarColor", testbrush);
}

【问题讨论】:

    标签: xaml uwp c++-cx


    【解决方案1】:

    UWP,是否可以通过编程方式添加 ResourceDictionary 值?

    当您更新newResourceDic 以上时,它会抛出Local values are not allowed in resource dictionary with Source set 异常,默认情况下,如果您想以编程方式添加 ResourceDictionary 值。我们建议您将newResourceDic 添加到应用程序ResourceDictionary.MergedDictionaries。然后使用App.Current.Resources 更新,如下所示

    Xaml

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="ms-appx:///TestResouce.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
    

    C#代码

    if (App.Current.Resources.ContainsKey("TitleBarColor"))
    {
        App.Current.Resources["TitleBarColor"] = new SolidColorBrush(Colors.Red);
        App.Current.Resources.Add("HighTitleBarColor", new SolidColorBrush(Colors.Bisque));
    
    }
    

    C++

    if (App::Current->Resources->HasKey(L"TitleBarColor")) {
        App::Current->Resources->Remove(L"TitleBarColor");
        Windows::UI::Color c;
        c.A = 255;
        c.R = 255;
        c.G = 0;
        c.B = 0;
        auto testbrush = ref new Windows::UI::Xaml::Media::SolidColorBrush(c);     
        App::Current->Resources->Insert("TitleBarColor", testbrush);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多