J'ai un ComboBox avec ItemsSource = "{DynamicResource testResource}". Le testResource est la ressource Application que j'ai définie dans le code C#.Essayer de comprendre les détails de l'affectation des ressources d'application
Ce que je constate est que si je charge la fenêtre befor Application créée, la ressource est pas chargé par ComboBox:
Window window = (Window)LoadXaml("Window1.xaml");
Application app = new Application();
Ce code fonctionne
Application app = new Application();
Window window = (Window)LoadXaml("Window1.xaml");
En outre, même si je créé le fenêtre avant l'application, je peux charger la ressource dernière dans le gestionnaire de clic de bouton.
Quelqu'un peut-il expliquer, que se passe-t-il? Pourquoi l'ordre est-il important?
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));
}
}