UWP:将值从UserControl传递到MainPage

时间:2017-06-27 10:52:17

标签: c# xaml user-controls uwp

我创建了一个UserControl,其中所有内容都在UserControl.xaml.cs中完成,我希望UserControl中的特定属性(称为“Value”)传递给在MainPage中创建的TextBlock。为了测试属性的访问,我在UserControl中创建了一个TextBlock,并通过Text={Binding Path=Value}绑定到文本“Value”,它工作正常。我如何从MainPage绑定TextBlock来实现相同的目的?

2 个答案:

答案 0 :(得分:1)

您可以使用Binding的ElementName部分来访问UserControl中的Value。要做到这一点,你必须给你的UserControl一个x:Name,然后像这样设置你的Binding:

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

答案 1 :(得分:1)

确保您已将属性创建为DependencyProperty。你可以使用下面的代码

来做到这一点
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(""));

您可以使用以下代码

获取XAML中的值
<TextBlock Text="{Binding ElementName=UserControl, Path=Value}"/>

(OR)

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

注意:使用x:Bind因为它效率高于Binding

相关问题