2014-02-17 39 views
1

我有一個WPF窗口:參考主窗口的字典從資源字典

<Window x:Class="MyUI.MainWindow" 
     and so on> 
    <Window.Resources> 
     <ResourceDictionary> 
      <Style TargetType="{x:Type s:SurfaceListBox}" x:Key="FatherStyle" > 
     </ResourceDictionary> 
    </Window.Resources> 
</Window> 

我有一個資源字典中MyResourceDictionary.xaml

<ResourceDictionary xmlns="........." 
        and so on > 
    <Style TargetType="{x:Type s:SurfaceListBox}" x:Key="ChildStyle" BasedOn="{StaticResource FatherStyle}" /> 
</ResourceDictionary> 

但是,當我嘗試引用ChildStyleMyUI.Window

<Window as shown in 1st block of code above> 
    <s:SurfaceListBox Style="{StaticResource ResourceKey=ChildStyle}" /> 
</Window> 

它告訴我它找不到FatherStyle。我讀here併合並在MyResourceDictionary.xaml字典:

<ResourceDictionary xmlns="........." 
        and so on > 
    <ResourceDictionary.MergedDictionaries> 
     <ResourceDictionary Source="MainWindow.xaml" /> 
    </ResourceDictionary.MergedDictionaries> 

    <Style ChildStyle as shown above /> 
</ResourceDictionary> 

現在它告訴我它無法找到ChildStyle。我如何正確引用它?

回答

1

您不能從另一個文件中引用包含在Window-type XAML文件中的資源字典。你需要做的是創建一個單獨的資源字典, 「Shared.xaml」 或什麼:

<ResourceDictionary ... > 
    <Style TargetType="{x:Type s:SurfaceListBox}" x:Key="FatherStyle" > 
</ResourceDictionary> 

現在引用共享一個從你的主窗口:

...也來自「MyResourceDictionary.xaml」:

<ResourceDictionary xmlns="........." 
       and so on > 
    <ResourceDictionary.MergedDictionaries> 
     <ResourceDictionary Source="Shared.xaml" /> 
    </ResourceDictionary.MergedDictionaries> 

    <Style TargetType="{x:Type s:SurfaceListBox}" x:Key="ChildStyle" BasedOn="{StaticResource FatherStyle}" /> 
</ResourceDictionary> 

現在在你的「MyUI.xaml」窗口中,你應該能夠訪問「ChildStyle」如你所料,通過引用「MyResourceDictionary」:

<ResourceDictionary xmlns="........." 
       and so on > 
    <ResourceDictionary.MergedDictionaries> 
     <ResourceDictionary Source="MyResourceDictionary.xaml" /> 
    </ResourceDictionary.MergedDictionaries> 

    <s:SurfaceListBox Style="{StaticResource ResourceKey=ChildStyle}" /> 
</ResourceDictionary> 
+1

謝謝!但是爲什麼我把fatherstyle放在window-type xaml文件中是因爲它包含事件處理程序。當事件處理程序與窗口xaml一起使用時,我將會有更容易的時間,因爲它們需要彼此共享數據。但既然不能完成,我只會按照你的方法去想另一種方式。謝謝! –

+1

啊,我發現這個解決了我的問題:http://stackoverflow.com/questions/5745001/xaml-combine-styles –