创建静态资源字典 [英] Creating static resource dictionary
本文介绍了创建静态资源字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个资源字典,我想将它与多个用户控件 xaml 文件合并.我只想创建此资源字典的一个实例.知道如何做到这一点吗?
I've created a Resource Dictionary that I want to merge with multiple usercontrol xaml files. I want only one instance of this Resource Dictionary to be created. Any idea how to do this?
注意:合并应仅通过 xaml 进行,而不能通过代码进行.
Note: Merge should happen through xaml only and not through code.
谢谢&问候,维沙尔
Thanks & Regards, Vishal
推荐答案
这个怎么样?
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 对象在多个词典之间动态选择.
You can use Type object to dynamically choose between multiple dictionaries.
这篇关于创建静态资源字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文