我需要动态更改 ResourceDictionary 文件中的 App.xaml。我尝试了以下代码:

ResourceDictionary newRes = new ResourceDictionary();
newRes.Source = new Uri("/PsyboInventory;component/TitleBarResource.xaml", UriKind.RelativeOrAbsolute);
this.Resources.MergedDictionaries.Clear();
this.Resources.MergedDictionaries.Add(newRes);

没有错误,但主题没有改变

最佳答案

在按钮单击中,您可以编写此代码


public partial class App : Application
    {
        public ResourceDictionary ThemeDictionary
        {
            // You could probably get it via its name with some query logic as well.
            get { return Resources.MergedDictionaries[0]; }
        }

        public void ChangeTheme(Uri uri)
        {
            ThemeDictionary.MergedDictionaries.Clear();
            ThemeDictionary.MergedDictionaries.Add(new ResourceDictionary() { Source = uri });
        }

    }

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary x:Name="ThemeDictionary">
                    <ResourceDictionary.MergedDictionaries>
                        <ResourceDictionary Source="/Themes/ShinyRed.xaml"/>
                    </ResourceDictionary.MergedDictionaries>
                </ResourceDictionary>
    </ResourceDictionary.MergedDictionaries>

关于c# - 如何动态更改 ResourceDictionary,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33867091/

10-11 08:07