尝试了解应用程序资源分配的详细信息

时间:2009-03-31 20:24:44

标签: wpf dynamicresource

我有一个带有ItemsSource =“{DynamicResource testResource}”的ComboBox。 testResource是我在C#代码中设置的Application资源。

我注意到的是,如果我加载Window befor Application,则ComboBox不会加载资源:

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

此代码有效

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

另外,即使我在应用程序中创建了窗口,我也可以在按钮点击处理程序中加载资源。

有人可以解释一下,会发生什么?为什么订单很重要?

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

1 个答案:

答案 0 :(得分:0)

不确定,但我猜是因为Application的资源仅在创建Application对象时加载。因此,如果您想要访问testResource,则需要在调用new Application()之后执行此操作。