FPGA
FPGA

Reputation: 3855

How do I use my Application Resources from another window?

In my App.xaml file I have:

<Application.Resources>
    <LocalViewModels:SharedSettingsViewModel x:Key="SharedSettingsViewModel"/>
    <LocalViewModels:ApplicationSpecificSettingsViewModel x:Key="ApplicationSpecificSettingsViewModel" />
</Application.Resources>

How can I use those resources in another window?

For example, if I had those resources in the same window I would do:

DataContext="{Binding Source={StaticResource ApplicationSpecificSettingsViewModel}}"
DataContext="{Binding Source={StaticResource ApplicationSpecificSettingsViewModel}}"

Upvotes: 2

Views: 271

Answers (1)

Kenn
Kenn

Reputation: 2769

While I agree with HighCore if you want to do it this is what you need to do. The following is a complete example.

Step one - create the viewmodel (which you have already done it seems)

namespace resourcesTest
{
    public class SharedViewModel
    {
        public string TestMessage
        {
            get { return "This is a test"; }
        }
    }
}

Step two - Add it to the app.xaml as a resource

<Application x:Class="resourcesTest.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:resourcesTest"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
         <local:SharedViewModel x:Key="SharedViewModel"></local:SharedViewModel>
    </Application.Resources>
</Application>

Step three - set the datacontext in your window - whichever one it may be and then you can make use of the data.

<Window x:Class="resourcesTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid DataContext="{Binding Source={StaticResource SharedViewModel}}">
        <Label Content="{Binding TestMessage}"></Label>
    </Grid>
</Window>

unless I am missing something that is what you are trying to do. Again, I wouldn't do it this way - I would use the application resources for styles and UI specific things only. Hopefully that helps.

Upvotes: 1

Related Questions