views:

63

answers:

1

I have a ComboBox with ItemsSource="{DynamicResource testResource}". The testResource is the Application resource that I set in C# code.

What I have noticed is that if I load Window befor Application created, the resource is not loaded by ComboBox:

Window window = (Window)LoadXaml("Window1.xaml");
Application app = new Application();

This code works

Application app = new Application();
Window window = (Window)LoadXaml("Window1.xaml");

Also, even if I created the window befor the application, I can load resource latter in button click handler.

Can some one explain, what happens? Why the order matters?

Window1.xaml:

<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <ComboBox ItemsSource="{DynamicResource testResource}" SelectedIndex="0"></ComboBox>
        <Button x:Name='testButton'>Test</Button>
    </StackPanel>
</Window>

C#

class Program
{
    [STAThread]
    public static void Main()
    {
        Window window = (Window)LoadXaml("Window1.xaml");
        Application app = new Application();
        SetupResource();

        (window.FindName("testButton") as Button).Click += new RoutedEventHandler(testButton_Click);
        window.Show();
        app.Run(window);
    }

    static void testButton_Click(object sender, RoutedEventArgs e)
    {
        SetupResource();
    }

    static void SetupResource()
    {
        List<string> list = new List<string>();
        list.Add("Hola");
        list.Add("Mundo");
        Application.Current.Resources["testResource"] = list;
    }

    static object LoadXaml(string fileName)
    {
        return XamlReader.Load(File.Open(fileName, FileMode.Open));
    }
}
A: 

Not sure, but I would guess because the Application's Resources are only loaded when the Application object is created. So if you want to access testResource, you need to do it after the call to new Application().

Anthony Brien