在 WPF 用户控件库中的用户控件之间共享资源的最简单方法是什么?

问题描述:

其中有一个 WPF 用户控件库和两个(或多个)用户控件.我需要在两个用户控件中使用相同的样式.我如何分享这种风格?例如:

There are a WPF User Control library and two (or more) User Controls in it. I need to use the same style in both user controls. How can I share this style? For example:

这是样式:

<Style x:Key="customLabelStyle" TargetType="Label">
    ...
</Style>

用户控件 A:

<UserControl x:Class="Edu.Wpf.Example.UserControlA"
   ...xmlns stuff... >
   <Grid>
      ... some xaml markup...
      <Label Style="{StaticResource customLabelStyle}"/>
   </Grid>
</UserControl>

用户控件 B:

 <UserControl x:Class="Edu.Wpf.Example.UserControlB"
   ...xmlns stuff... >
   <Grid>
      ... some another xaml markup...
      <Label Style="{StaticResource customLabelStyle}"/>
   </Grid>
</UserControl>

那么如何在不涉及应用程序 app.xaml 资源字典的情况下在库中的用户控件之间共享这种样式?

So how can I share this style between user controls in the library without involving of the application app.xaml resource dictionary?

更新

我可以将 Themes\Generic.xaml 添加到我的库中并在那里定义样式.但在这种情况下,我必须使用 ComponentResourceKey 作为样式的键.正确的?它很长而且不是很方便的表达...

I can add Themes\Generic.xaml into my library and define the style there. But in this case I have to use ComponentResourceKey as the key of the style. Right? It's long and not very handy expression...

您可以在单独的 ResourceDictionary 中定义共享资源,然后将它们合并到您的 UserControl 中使用 MergedDictionaries 的资源.

You can define the shared resources in a separate ResourceDictionary, then merge them into your UserControl's Resources using MergedDictionaries.