简体   繁体   English

Silverlight 3.0 - 如何从UserControl访问MainPage控件值

[英]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. 我需要从MainPage检索一些控件值到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). 在这个UserControl中,我需要能够获取Frame.ActualWidth和Frame.ActualHeight值(在这种情况下,Frame元素在MainPage中,UserControl通过xaml加载到MainPage的Grid中)。 Does someone have a sample? 有人有样品吗? Thank you 谢谢

Josimari Martarelli ESL Sistemas Logísticos Silverlight UI Design Josimari Martarelli ESLSistemasLogísticosSilverlightUI设计

jmartarelli@logfacil.com.br 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. 在这样的实例中,我经常会使用我的MainPage类对其自身进行公共静态引用,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: 我将它在构造函数中设置为“this”,然后当我需要从用户控件中向下访问MainPage时,我将调用类似于:

MainPage.Instance. 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. 首先,我在App类中创建了一个静态方法,该方法遍历父项的层次结构,直到找到基于名称的匹配项。 This can be used for more than just MainPage. 这不仅可以用于MainPage。 Everything in the hierarchy should be derived from the FrameworkElement class. 层次结构中的所有内容都应该从FrameworkElement类派生。

    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"); 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; Login lp = (Login)Application.Current.RootVisual;
You can use the parameter that you created in login page. 您可以使用在登录页面中创建的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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