【问题标题】:Override Generic.xaml Resource Dictionary resources from another project in same solution覆盖同一解决方案中另一个项目的 Generic.xaml 资源字典资源
【发布时间】:2014-09-30 13:27:20
【问题描述】:

我有一个解决方案,其中我有一个 Windows Phone App 项目和一个 ClassLibrary,它本身具有 TemplatedControl.cs,其默认样式在 ClassLibrary/Themes/Generic.xaml 资源字典中引用。

- MySolution
    - WPApp_Project
        - MainPage.xaml/MainPage.xaml.cs
        - App.xaml/App.xaml.cs

    - ClassLibrary_Project
        - Themes
            - Generic.xaml
        - View
            - TemplatedControl.cs
        - ViewModel
            - TemplatedViewModel.cs
            - ViewModelLocator.cs

例如,我在 Generic.xaml 文件中定义了这个:

<SolidColorBrush x:Key="MyBrush" Color="Gold"/>

如何从我的 WP 应用程序中更改此 SolidColorBrush 的值,使其影响到我的 ClassLibrary 中使用此资源的每个元素?

【问题讨论】:

    标签: c# wpf xaml resourcedictionary generic.xaml


    【解决方案1】:

    您基本上只需要在已加载通用值之后用另一个值覆盖 x:Key。您可以通过动态加载包含您要覆盖的键的资源文件来做到这一点。

    要动态加载 XAML 资源字典,您可以执行以下操作:

    Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/WPF.Common.UI;component/Resources/Dictionaries/ApplicationResourceDictionary.xaml") });
    

    【讨论】:

    • 这不起作用。问题是我的 WPApp 中没有直接引用 Generic.xaml。如果我尝试在 App.xaml 中添加 Generic.xaml 的 MergedResource 字典,则会引发异常。
    • 如果DynamicResource 可用,它可能会起作用。
    • @ricochite 请参阅更新/编辑。您不能使用上面的代码来访问您的 MergedDictionaries?我在 Windows Phone 项目中使用上面的罚款
    • 问题是我需要的ResourceDictionary在ClassLibrary项目中,是Generic.xaml文件。我不是在使用两个 WP 项目,而是在使用一个 WP 项目和具有 Themes/Generic.xaml ResourceDictionary 的 ClassLibrary 项目。关于您的更改,它仍然不起作用,但感谢您的帮助。 :)
    【解决方案2】:

    我设法找到了一种方法来做到这一点。由于我在Generic.xaml 中有一个带有属性的TemplatedViewModel.cs,因此我基本上为我想要更改的内容创建了额外的属性,即,如果我想更改TextBlock 的颜色,我在@ 中添加以下内容987654323@:

    <TextBlock Content="I am a TextBlock" Foreground="{Binding Path=HappyColor}" />
    

    在我的 WPApp 中,我得到一个 TemplatedViewModel.cs 的实例并将其设置为新颜色:

    TemplatedViewModel viewModel = ViewModelLocator.TemplatedStatic;
    viewModel.HappyColor = "#00FF00";
    

    理想情况下,我希望能够在 XAML 中的 ResourceDictionary 中设置属性,但我无法做到。所以在接下来的几天里,如果有人能告诉我怎么做,我会把他们的回复标记为答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-06
      • 2022-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多