2014-10-03 67 views
3

我在WPF中有一個簡單包含框架元素的窗口。該框架顯示一個頁面;顯示的頁面會根據用戶交互進行更改。將資源詞典應用於WPF框架中的頁面

<Window x:Class="MyWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Height="720" Width="1280"> 
    <Grid> 
     <Frame Source="{Binding Source={StaticResource MainPageIntent}, Path=Path}"/> 
    </Grid> 
</Window> 

我希望出現在該幀共用一個資源字典,使他們都可以在一個共同的方式來稱呼所有頁面。

現在,我有這樣的事情在每一個頁面,這個窗口負載:

<Page.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="/ResourceDictionaries/BaseControlStyles/MenuStyle.xaml"/> 

我希望,我可能只是能夠設置資源字典上的窗口,他們會「繼承」這些資源,但似乎並非如此。我想這樣的事情,但在MenuStyle.xaml發現樣式沒有應用由框架加載頁面內的控件:

<Window x:Class="MyWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Height="720" Width="1280"> 
    <Window.Resources> 
     <ResourceDictionary> 
      <ResourceDictionary.MergedDictionaries> 
       <ResourceDictionary Source="/ResourceDictionaries/BaseControlStyles/MenuStyle.xaml"/> 
      </ResourceDictionary.MergedDictionaries> 
     </ResourceDictionary> 
    </Window.Resources> 
    <Grid> 
     <Frame Source="{Binding Source={StaticResource MainPageIntent}, Path=Path}"/> 
    </Grid> 
</Window> 

的是,有辦法在窗位,使得所有定義的樣式在子框架中加載的頁面將使用這些樣式?

注:我不希望在我的應用程序應用這些樣式的所有窗口,所以把這個資源字典在我的App.xaml不會出現是一個有效的解決方案。

+0

Window不是頁面的邏輯父。因此它無法從其字典中解析資源。所以,最後的手段是將它合併到應用程序資源中,或者將它合併到Page的構造函數中的每個頁面實例中。 – 2014-10-03 16:24:18

回答

1

如果你想寫一次以避免代碼重複,你可以把它寫在代碼後面。在框架ContentRendered上,您可以編寫代碼將資源添加到正在加載的頁面。

<Frame Name="fr_View" ContentRendered="fr_View_ContentRendered"/> 


private void fr_View_ContentRendered(object sender, System.EventArgs e) 
{ 
    ResourceDictionary myResourceDictionary = new ResourceDictionary(); 
    myResourceDictionary.Source = new Uri("Dictionary1.xaml", UriKind.Relative); 
    (fr_View.Content as System.Windows.Controls.Page).Resources.MergedDictionaries.Add(myResourceDictionary); 
} 

這個鏈接看看: Set up application resources from code