UWP:将值从 UserControl 传递到 MainPage

UWP: Passing value from UserControl to MainPage

我创建了一个 UserControl,其中的所有操作都在 UserControl.xaml.cs 中完成,我希望将来自 UserControl 的特定 属性(称为 "Value")传递给一个 TextBlock,它是在主页面中创建。为了测试 属性 的访问权限,我在 UserControl 中创建了一个 TextBlock,并通过 Text={Binding Path=Value} 将文本绑定到 "Value",它工作正常。我如何必须从 MainPage 绑定 TextBlock 才能实现相同的目的?

您可以使用绑定的 ElementName 部分从 UserControl 访问值。为此,您必须为您的 UserControl 提供一个 x:Name,然后像这样设置您的 Binding:

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

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

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}"/>

(或)

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

注意:使用x:Bind因为它比Binding

更有效率