Apply ResourceDictionary to pages in frame in WPF

I have a window in WPF that just contains a Frame element. The frame displays the page; the page displays the change based on user interaction.

<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>

      

I would like all the pages that appear in this frame to share a common resource dictionary so that they can all be styled in the usual way.

Right now I have something like this on every page loaded by this window:

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

      

I was hoping that I could just set the resource dictionary in the window and they would "inherit" those resources, but that doesn't seem to be the case. I've tried something like this, but the styles found in MenuStyle.xaml don't apply controls inside the frame loaded page:

<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>

      

Is there a way to define window-level styles so that all pages loaded in child frames use those styles?

Note. ... I don't want to apply these styles to all windows in my application, so placing this ResourceDictionary in my App.xaml doesn't seem to be a valid solution.

+3


source to share


1 answer


If you want to write it once to avoid code duplication, you can write it in the code behind. In the ContentRendered frame, you can write code to add the resource to the loaded page.

<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);
}

      



Take a look at this link: Configure App Resources From Code

+1


source







All Articles