简体   繁体   English

将字符串传递给用户控件

[英]passing a string to a User Control

I'm approaching to Metro App world in this days, please be gentle. 我最近正在接近Metro App世界,请保持温柔。 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? 如何将参数从页面传递到另一个页面的UserControl?

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: 然后使用您的NavigatedTo方法:

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. 如果尝试这种方法,请记住将用户控件的属性设置为Dependency属性而不是CLR属性。 I wrote an article on binding if you want a better explaination http://blog.jerrynixon.com/2012/10/xaml-binding-basics-101.html 如果您想要更好的解释,我写了一篇关于绑定的文章http://blog.jerrynixon.com/2012/10/xaml-binding-basics-101.html

Best of luck! 祝你好运!

Assuming usercontrol is part of navigated page, you have to do set Property of User Control on OnNavigatedTo override. 假设usercontrol是导航页面的一部分,则必须在OnNavigatedTo覆盖上设置User Control的属性。

Example: 例:

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

Suppose this user control is part of MyPage 假设此用户控件是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.
     }
   }

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

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