霜月幻夜
霜月幻夜

Reputation: 85

how to set DataContext when mainWindow is null?

class Program : Application
{
    [STAThread]
    public static void Main()
    {

        Program app = new Program();
        app.StartupUri = new Uri("../../LoginWindow.xaml", UriKind.Relative);

       //app.MainWindow is null
        app.Run();

    }

    virtual protected void OnStartUp(StartupEventArgs e)
    {
        MessageBox.Show("Start up");

    }
}

//the MainWindow of app is null, so how can I set the DataContext to the LoginWindow(is an UserControl) in void Main() //for some reason, there should not be a window class, I want to directly start the UserControl

Upvotes: 2

Views: 340

Answers (2)

17 of 26
17 of 26

Reputation: 27382

A much easier way to do this is to subscribe to the Startup event of your application:

App.xaml:

<Application x:Class="MyApp"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         Startup="App_Startup" />

App.xaml.cs:

public partial class App
{
    private void App_Startup(object sender, StartupEventArgs e)
    {
        var view = new MainView { DataContext = new MainVM() };
        view.Show();
    }
}

Upvotes: 1

Il Vic
Il Vic

Reputation: 5666

Well this is not the proper way which a WPF application starts in. I do not know why you need to create a Main method as your application were a Windows.Form one. Anyway you can do what you need looking at this blog.

Basically you

need to change the application's build action from "Application Definition" to "Page", create a constructor that calls "InitializeComponent", and write your Main() by eventually calling one of the application’s "Run" method overloads

Then your code will become

class Program : Application
{
    public Program()
    {
        InitializeComponent();
    }

    [STAThread]
    public static void Main()
    {
        LoginWindow loginWindow = new LoginWindow();
        /* Here you can set loginWindow's DataContext */ 
        Program app = new Program();
        app.Run(window);
    }
}

Upvotes: 0

Related Questions