passing a string to a User Control

允我心安 提交于 2020-02-02 16:11:18

问题


I'm approaching to Metro App world in this days, please be gentle. Here's the problem:

a page receives a string from another page

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    Title.Text = e.Parameter.ToString();
}

and I need to pass this string to an User Control of the receiving page.

How can I pass a parameter from a page to an UserControl of another page?


回答1:


Like this:

Add a property to your user control:

public string MyText { get; set; }

Give your user control a name.

<src:TopBarControl x:Name="MyTopBarControl" />

Then use your NavigatedTo method:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    var _TextParam = e.Parameter.ToString();
    this.MyTopBarControl.MyText = _TextParam;
}

This will feed your User Control what it needs.

You could also bind to it by setting the parameter to some public property of the page. If you attempt this approach, please remember to make the User Control's property a Dependency property and not a CLR property. I wrote an article on binding if you want a better explaination http://blog.jerrynixon.com/2012/10/xaml-binding-basics-101.html

Best of luck!




回答2:


Assuming usercontrol is part of navigated page, you have to do set Property of User Control on OnNavigatedTo override.

Example:

 class MyUserControl : UserControl
 {
    public object Parameter {get;set;}
 }

Suppose this user control is part of MyPage

  class MyPage : Page
  {
    private MyUserControl myUserControl; // It is only for illustrations, Otherwise it goes to .designer.cs

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
       Title.Text = e.Parameter.ToString();
       myUserControl.Parameter = e.Parameter; // This is how to set the parameter in usercontrol.
     }
   }


来源:https://stackoverflow.com/questions/14219989/passing-a-string-to-a-user-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!