【问题标题】:Dynamically change implicit style动态改变隐式风格
【发布时间】:2012-01-25 06:47:30
【问题描述】:

现在我的应用中有一些隐式样式的 TabItem。我想在我的应用中添加“夜间模式”并改变我的风格。我该怎么办?

【问题讨论】:

    标签: wpf xaml styles


    【解决方案1】:

    您可以使用合并的字典来做到这一点。将所有“正常”样式放入字典中,并默认将其添加到应用资源中:

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Styles/Normal.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
    

    然后你可以删除当前字典并动态加载另一个:

    private void ChangeStyles()
    {
        App.Current.Resources.MergedDictionaries.Clear();
    
        StreamResourceInfo resInfo = App.GetResourceStream(new Uri("Styles/NewStyles.xaml", UriKind.Relative));
        XDocument xaml = XDocument.Load(resInfo.Stream);
        ResourceDictionary resource = XamlReader.Load(xaml.ToString()) as ResourceDictionary;
    
        App.Current.Resources.MergedDictionaries.Add(resource);
    }
    

    【讨论】:

    • XamlReader.Load 不将字符串作为 arg。至少在 4.0
    • 抱歉,我从 Silverlight 项目中获取了该代码。在 WPF 中,它需要一个 XmlReader,它可以使用 XmlReader.Create 从流中构建。
    【解决方案2】:

    阿方索的想法是对的…… 但你必须在 WPF 中这样做

    App.Current.Resources.MergedDictionaries.Clear(); 
    Uri uri = new Uri("/Resources/GlassButton5Night.xaml", UriKind.Relative);
    var resDict = Application.LoadComponent(uri) as ResourceDictionary;
    App.Current.Resources.MergedDictionaries.Add(resDict);
    

    并且您已确保在正确的级别重置您的 MergedDictionaries

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-11
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 2017-09-01
      • 2019-05-08
      • 2015-06-23
      • 2018-03-28
      相关资源
      最近更新 更多