简体   繁体   English

UWP:将值从UserControl传递到MainPage

[英]UWP: Passing value from UserControl to MainPage

I have created a UserControl where everything is done in the UserControl.xaml.cs and I want a specific property (called "Value") from the UserControl to be passed to a TextBlock which is created in the MainPage. 我创建了一个UserControl,其中所有操作都在UserControl.xaml.cs中完成,我希望将UserControl中的特定属性(称为“值”)传递给在MainPage中创建的TextBlock。 To test the access of the property, I have created a TextBlock within the UserControl and Bind to Text to "Value" via Text={Binding Path=Value} and it works fine. 为了测试对属性的访问,我已经在UserControl中创建了一个TextBlock,并通过Text={Binding Path=Value}将文本绑定到“ Value”,并且工作正常。 How do I have to bind the TextBlock from the MainPage to achieve the same? 我如何从MainPage绑定TextBlock来实现相同目的?

You might be able to use the ElementName part of the Binding to access the Value from the UserControl. 你也许能够使用ElementName绑定的一部分,从用户控件访问值。 To do this you'll have to give your UserControl an x:Name then set up your Binding like so: 为此,您必须给UserControl一个x:Name然后像下面这样设置Binding:

Text="{Binding Value, ElementName=MyUserControl}"

Make sure you have created your Property as a DependencyProperty. 确保已将属性创建为DependencyProperty。 You can do it using below code 您可以使用以下代码进行操作

public string Value
{
    get { return (string)GetValue(ValueProperty); }
    set { SetValue(ValueProperty, value); }
}

public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register("Value", typeof(string), typeof(UserControl ), new PropertyMetadata(""));

You can get the value in XAML using below code 您可以使用以下代码在XAML中获取值

<TextBlock Text="{Binding ElementName=UserControl, Path=Value}"/>

(OR) (要么)

<TextBlock Text="{x:Bind CustomInkControl.Value, Mode=OneWay}"/>

Note: Use x:Bind because It is efficient than Binding 注意:使用x:Bind是因为它比Binding更有效

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

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