Application class in winforms and WPF - wpf

I am new to GUI development, i was trying to develop a sample ui application using winforms and WPF.
I found some of the code missing in WPF
namespace WindowsFormsApplication3
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Why this code is not present in WPF when the project is created
Why we are using Application class, what is the need of this class?

WPF uses the Application.Xaml and Application.cs to start your application.
It start your application and you can override some methods and choose how to start your application, apply come general configuration and error handling for your application

This code is not present because in the app.xaml definition there is usually a StarupURI="window1.xaml" attribute that allow the WPF infrastructure to wire the startup code behind the scene.
Of course you can create a custom bootsrapper, you need to remove the StartupURI attribute and intercept the Application startup to create/show a window:
public partial class App
{
protected override void OnStartup(StartupEventArgs e)
{
try
{
var mainView = new MainView();
mainView.Show();
mainView.DataContext = new YourDataContext();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}

Related

How to "restore" SynchronizationContext when using custom startup?

My app works fine, but now I wanted to have custom startup, so I could catch any errors, add my logging from the start, etc.
So I used approach as shown in this answer What code controls the startup of a WPF application?
[STAThread]
public static void Main(string[] args) {
//include custom startup code here
var app = new MyApplication();//Application or a subclass thereof
var win = new MyWindow();//Window or a subclass thereof
app.Run(win); //do WPF init and start windows message pump.
}
It works fine with one exception -- SynchronizationContext.Current is null. And I need it :-)
So how to correctly make custom startup and have synchronization context?
Don't create your own Main method. Override the OnStartup method in your App.xaml.cs file:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var win = new MyWindow();
win.Show();
}
}
Then you will get a SynchronizationContext as usual.
Don't forget to remove the StartupUri attribute from the <Application> root element of your App.xaml file.

How to customize startup of WPF application?

When a new WPF Application project is created, MainWindow.xaml, App.xaml and their corresponding code behind classes are automatically generated. In the App.xaml there is an attribute that defines which window is going to be run initially and by the default it's StartupUri="MainWindow.xaml"
I have created a new Dispatcher class in the same project. At startup, I want the instance of that class Dispatcher to be constructed and then one of its method to run. That method would actually create and show the MainWindow window. So how do I modify the App.xaml or App.xaml.cs in order to make it happen? Or, if it cannot be done by App, how should I implement it? Thanks.
You can remove the StartupUri attribute from the App.xaml.
Then, by creating an override for OnStartup() in the App.xaml.cs, you can create your new instance of your Dispatcher class.
Here's what my quick app.xaml.cs implementation looks like:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
new MyClassIWantToInstantiate();
}
}
}
Update
I recently discovered this workaround for a bug if you use this method to customize app startup and suddenly none of the Application-level resources can be found.
Try to use the Startup event (class Application) - MSDN.
You can show MainWindow in this event handler - after you create a Dispatcher instance.
1.In App.xaml, To replace the StartupUri with a subscription to the Startup event.
Use the event in App.xaml.cs .
For instance,
Startup="Application_Startup" in .xaml.
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
// Create the startup window
MainWindow wnd = new MainWindow();
// Do stuff here, e.g. to the window
wnd.Title = "Something else";
// Show the window
wnd.Show();
}
}

Where to place and configure IoC container in a WPF application?

I am working on a middle sized WPF application (MVVM) that should be extensible and maintainable in the future. Thus I decided to use an IoC container (Unity in this case) to keep things flexible.
However I am not sure where to place and configure Unity in a WPF application.
I guess container should be accessible globally so it should probably go to Application class. But should I make it as static property? Should I configure it in Application_Startup() event handler?
Eg:
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public static UnityContainer MyUnityContainer;
private void Application_Startup(object sender, StartupEventArgs e)
{
// instantiate and configure Unity
}
}
This way I will be able to access container from any place in the application via static property:
App.MyUnityContainer
I guess this is one way to do it but I am not sure if there are better practices for this issue, specifically for WPF apps.
Have a look at the Composition Root Pattern. What you want to do is to initialize it in your Startup event handler and forget about its existence for the rest of the application.
You are trying to implement the Service Locator Pattern, which according to many is an inferior solution to this problem.
Let me post what I've concluded and hopefully it'll help people out. Correct if there's anything wrong! :P
I guess we'd be looking into something like this:
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
UnityContainer myUnityContainer = new UnityContainer();
//make sure your container is configured
myUnityContainer.RegisterType<ISomeDependency, SomeDependencyImplementation>();
myUnityContainer.RegisterType<IMainWindow, MainWindow>();
myUnityContainer.Resolve<IMainWindow>().Show();
}
}
public partial class MainWindow : Window, IMainWindow
{
private ISomeDependency _someDependency;
public MainWindow(ISomeDependency someDependency)
{
_someDependency = someDependency;
}
}
Note there are no globals or singletons, the container survives as long as MainWindow does and all dependencies behind this point of entry further into the composition graph are automagically resolved as long as the container knows about them.
As per new version of Unity container, we have to register it's own instance as well to get it in view models via constructor injection.
App.xaml.cs file:
protected override void OnStartup(StartupEventArgs e)
{
var unityIoC = new UnityContainer();
unityIoC.RegisterTypes(AllClasses.FromAssembliesInBasePath(), WithMappings.FromMatchingInterface, WithName.Default);
unityIoC.RegisterInstance(typeof(IUnityContainer), unityIoC);
}
View Model class
[InjectionConstructor]
public MyViewModel(IUnityContainer container)
{
}
Now unity container would be available for us in view model and can be used to resolve.

WPF Prism: Problem with creating a Shell

I just started learning Prism and trying to use it with MEF in a test WPF application.
Based on "WPF Hands-On Lab: Get Started with the Prism
Library" example in the Prism4 documentation, in a test WPF project I renamed MainWindow class to Shell.
My Bootstrapper class has the following code (also based on the Lab example):
class Bootstrapper : MefBootstrapper
{
protected override DependencyObject CreateShell()
{
return new Shell();
}
protected override void InitializeShell()
{
Application.Current.MainWindow = (Shell)this.Shell;
Application.Current.MainWindow.Show();
}
...
App.xaml.cs code:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Bootstrapper bootstrapper = new Bootstrapper();
bootstrapper.Run();
}
}
When I try to run the app even without exporting any module in it, I get an error:
"Cannot locate resource 'mainwindow.xaml'."
What am I doing wrong?
When you renamed your class did mainwindow.xaml get renamed to shell.xaml?
But the code/config is still pointing to the original name.

load silverlight controls in asp.net page

I have a silverlight project which contains 2 silverlight controls Control_1 and Control_2. Please note that its in same app.Now I have asp.net project which will use any of these silverlight control (either Control_1 or Control_2).
Challenge is how do I tell silverlight which control to load. I used param property in html object to pass the parameters and tell the app which control to load at runtime?
But what if there are more than 2 controls in same project? We cannot have a long switch case statement in the app file only to load the controls. Is there any better way?
No, There isn't, and this is not about Silverlight itself, this is normal logic.
In your App.xaml file, put this:
using System.Windows; // Application, StartupEventArgs
namespace SilverlightApplication
{
public partial class App : Application
{
public App()
{
InitializeComponent();
}
private void Application_Startup(object sender, StartupEventArgs e)
{
// Specify the main application UI
if(SomeCondition == true)
this.RootVisual = new Control1();
else
this.RootVisual = new Control2();
// In the same way, you may define a switch statment
}
}
}
You may decide what that condition is by passing parameters to the XAP file, and finally you access those by accessing e.InitParams in Application_Startup
For more info: Application.RootVisual

Resources