2010-06-14 2 views
5

여러 usercontrol xaml 파일과 병합하려는 리소스 사전을 만들었습니다. 이 리소스 사전의 한 인스턴스 만 만들길 원합니다. 어떤 생각을 어떻게 할 것인가?정적 리소스 사전 만들기

참고 : 병합은 코드가 아닌 xaml에서만 수행해야합니다.

감사 & 감사합니다, 이씨는 진정한 글로벌의 경우

답변

3

어때?

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 개체를 사용할 수 있습니다.

+0

고맙습니다 decyclone !!! 귀하의 솔루션은 나를 위해 일했습니다 :-) – Vishal

1

는, 어쩌면 당신이 사전 App.xaml을 병합 수 있을까?

+0

아니요. 전 세계가 아닙니다. 클래스 라이브러리 안에 있으며 주요 실행 가능 프로젝트는이 리소스 사전을 인식하지 못합니다. – Vishal

관련 문제