Domanda

In the main view model of my app, I am creating an instance of a class that looks something like this (this has been simplified)

public class MyClass
{ 
    public void MyFunction()
    {
        var root = Window.Current.Content as Frame;
        var mainPage = root.Content as Page;
    }
}

and then I am calling MyFunction(), but the root.Content property is always null.

Why is this?

root is not null

The view is of type Page

Thanks

È stato utile?

Soluzione

you are trying to do this in MainViewModel's constructor at that time I think the main page is not fully initialized that is why the Content is null. If you try to do that in some other page it works fine and this is strange for me that in MainPage(loadingPage)'s ViewModel It is not working. I have tested this both cases.

One work around is that on in loaded event handler of the main page send some message to the ViewModel. and in that message handler call MyFunction. it will work.

    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        Messenger.Default.Send<string,MainViewModel>("MainLoaded");
    }

In MainPage ViewModel

 public MainViewModel()
    {
        Messenger.Default.Register<string>(this, (action) =>
        {
            if (action == "MainLoaded")
            {
                MyClass cls = new MyClass();
                cls.MyFunction();

            }
        });
   }

Hope this helps

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top