我找到了一个解决方案,它在设计时也能工作(至少在VS2010中):
public static class Resource
{
private static readonly Dictionary<Uri, ResourceDictionary> SharedDictinaries = new Dictionary<Uri, ResourceDictionary>();
private static void onMergedDictionaryChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)
{
FrameworkElement el = source as FrameworkElement;
if (el == null)
return;
Uri resourceLocator = new Uri(GetMergedDictionary(source), UriKind.Relative);
ResourceDictionary dictionary;
if (SharedDictinaries.ContainsKey(resourceLocator))
dictionary = SharedDictinaries[resourceLocator];
else
{
dictionary = (ResourceDictionary)Application.LoadComponent(resourceLocator);
SharedDictinaries.Add(resourceLocator, dictionary);
}
el.Resources.MergedDictionaries.Add(dictionary);
}
public static readonly DependencyProperty MergedDictionaryProperty =
DependencyProperty.RegisterAttached("MergedDictionary", typeof (String), typeof (Resource), new FrameworkPropertyMetadata(null, onMergedDictionaryChanged));
[AttachedPropertyBrowsableForType(typeof(FrameworkElement))]
public static String GetMergedDictionary(DependencyObject source)
{
return (String) source.GetValue(MergedDictionaryProperty);
}
public static void SetMergedDictionary(DependencyObject source, String value)
{
source.SetValue(MergedDictionaryProperty, value);
}
}
这个附加属性可以应用于 FrameworkElement。假设 customLabelStyle 在 Edu.Wpf.Example 项目的 Styles.xaml 字典中定义。因此,可以通过以下方式应用此样式:
<UserControl x:Class="Edu.Wpf.Example.UserControlA"
...
xmlns:res="clr-namespace:Edu.Wpf.Example.Resources"
res:Resource.MergedDictionary="/Edu.Wpf.Example;component/Resources/Styles.xaml">
...
<Label Style="{StaticResource customLabelStyle}"/>
</UserControl>