2010-06-14 34 views
5

Tôi đã tạo một Từ điển tài nguyên mà tôi muốn hợp nhất với nhiều tệp xaml usercontrol. Tôi muốn chỉ có một thể hiện của từ điển tài nguyên này được tạo ra. Bất kỳ ý tưởng làm thế nào để làm điều này?Tạo từ điển tài nguyên tĩnh

Lưu ý: Hợp nhất chỉ xảy ra thông qua xaml và không thông qua mã.

Cảm ơn & Kính trọng, Vishal

Trả lời

3

Làm thế nào về điều này?

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> 

Bạn có thể sử dụng loại đối tượng để tự động lựa chọn giữa nhiều từ điển.

+0

Cảm ơn rất nhiều decyclone !!! Giải pháp của bạn làm việc cho tôi :-) – Vishal

1

Nếu đó là toàn cầu thực sự, có lẽ bạn có thể kết hợp từ điển này để App.xaml?

+0

Không. Nó không phải toàn cầu. Nó nằm bên trong một thư viện lớp và dự án thực thi chính là không nhận thức được từ điển tài nguyên này. – Vishal

Các vấn đề liên quan