创建静态资源字典

6

我已经创建了一个资源字典,我想将它与多个用户控件的xaml文件合并。我希望只创建一个此资源字典的实例。您有什么好的方法吗?

注意:合并应该只通过xaml完成,而不是通过代码。

谢谢 & 致意, Vishal

2个回答

4
这个怎么样?
class DictionaryExtensions
{
    public static ResourceDictionary MyResourceDictionary;

    static DictionaryExtensions()
    {
        MyResourceDictionary = new ResourceDictionary();
        Style buttonStyle = new Style() { TargetType = typeof(Button) };
        buttonStyle.Setters.Add(new Setter(Button.MarginProperty, new Thickness(5)));
        buttonStyle.Setters.Add(new Setter(Button.PaddingProperty, new Thickness(5)));
        buttonStyle.Setters.Add(new Setter(Button.MaxWidthProperty, 100.0d));
        MyResourceDictionary.Add("buttonStyle", buttonStyle);
    }

    public static Type GetMyDictionary(DependencyObject obj)
    {
        return (Type)obj.GetValue(MyDictionaryProperty);
    }

    public static void SetMyDictionary(DependencyObject obj, Type value)
    {
        obj.SetValue(MyDictionaryProperty, value);
    }

    // Using a DependencyProperty as the backing store for MyDictionary.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyDictionaryProperty =
        DependencyProperty.RegisterAttached("MyDictionary", typeof(Type), typeof(UserControl), new UIPropertyMetadata(new PropertyChangedCallback(OnMyDictionaryChanged)));

    public static void OnMyDictionaryChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is UserControl)
        {
            (d as UserControl).Resources.MergedDictionaries.Add(MyResourceDictionary);
        }
    }
}

XAML:

<UserControl x:Class="WpfSOTest.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:WpfSOTest"
         mc:Ignorable="d"
         d:DesignHeight="300"
         d:DesignWidth="300"
         local:DictionaryExtensions.MyDictionary="{x:Type ResourceDictionary}">
<Grid>
    <StackPanel>
        <Button Style="{StaticResource buttonStyle}"
                Content="Button1" />
        <Button Style="{StaticResource buttonStyle}"
                Content="Button2" />
    </StackPanel>
</Grid>

您可以使用Type对象动态选择多个字典。


1

如果它真正是全局的,也许你可以将这个字典合并到 App.xaml 中?


不是全局的。它在一个类库中,主可执行项目不知道这个资源字典。 - Vishal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接