'What is the proper way to run code on application start in C# WPF?
I need to populate a listbox with the names of directories so where would I put my method to run when the application starts (MainWindow, Window_Loaded or something)?
Solution 1:[1]
What actually happens is your XAML is complied and run in by the InitializeComponent() method call in the constructor of you MainWindow.
To use your ViewModel create your ListBox in XAML and bind ItemsSource to a collection of items then define a template of how each item should look - here would be a good place to start: http://msdn.microsoft.com/en-us/library/ms752347.aspx#binding_to_collections. Once you use this method you will realise the benefits when maintaining your code (even when your view changes and you have to update your UI it is simple) and the benefit of separating design from you code.
If you do want to use code behind instead of XAML you can assign a handler to the Window.Loaded event - beware though this can occur more than once so use a flag therein to see it has not already run.
While there are benefits of using MVVM - I dont take it as do everything in XAML - I would define my ListBox, template etc. in XAML but it you want conditional binding or something I find it easier to do so in code such as:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (!this.hasLoaded)
{
this.hasLoaded = true;
DirectoryInfo di = new DirectoryInfo("."); // "." is the current dir we are in
FileInfo[] files = di.GetFiles();
List<string> fileNames = new List<string>(files.Length);
foreach(FileInfo fi in files)
fileNames.Add(fi.Name);
this.listBox1.ItemsSource = fileNames;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Robert Harvey |
