简体   繁体   中英

Silverlight 3.0 - How to access a MainPage control value from an UserControl

I need to retrieve some control values from the MainPage to an UserControl. In this UserControl I need to be able to get the Frame.ActualWidth & Frame.ActualHeight values (in this case, the Frame element is in the MainPage and the UserControl is loaded inside a MainPage's Grid via xaml). Does someone have a sample? Thank you

Josimari Martarelli ESL Sistemas Logísticos Silverlight UI Design

jmartarelli@logfacil.com.br

MainPage m =(MainPage)Application.Current.RootVisual;

In instances like this I'll often use have my MainPage class have a public static reference to itself, Instance. I'll set it this "this" in the constructor and then when I need access to the MainPage from down in a user control I'll just call something like:

MainPage.Instance. Foo

First I created a static method in the App class that walks up the hierarchy of parents until it finds a match based on name. This can be used for more than just MainPage. Everything in the hierarchy should be derived from the FrameworkElement class.

    public static FrameworkElement GetParentByName(FrameworkElement currentPage, 
string ParentName)
    {

        FrameworkElement fe = (FrameworkElement)currentPage.Parent;

        // Walk your way up the chain of Parents until we get a match
        while(fe.GetType().Name != ParentName)
            fe = (FrameworkElement)fe.Parent;

        return fe;

    }

Then to use this I just call something like:

MainPage m = (MainPage)App.GetParentByName(this, "MainPage");

If you are using Login page then you have to cast using your login page.

ie Login lp = (Login)Application.Current.RootVisual;
You can use the parameter that you created in login page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM