【问题标题】:UWP: Passing value from UserControl to MainPageUWP:将值从 UserControl 传递到 MainPage
【发布时间】:2017-06-27 10:52:17
【问题描述】:

我创建了一个用户控件,其中所有操作都在 UserControl.xaml.cs 中完成,我希望将用户控件中的特定属性(称为“值”)传递给在 MainPage 中创建的 TextBlock。为了测试对属性的访问,我在 UserControl 中创建了一个 TextBlock,并通过 Text={Binding Path=Value} 将文本绑定到“值”,它工作正常。我如何必须从 MainPage 绑定 TextBlock 才能达到相同的效果?

【问题讨论】:

  • 是否要将UserControl 中的Value 属性绑定到MainPage 中的TextBlock?如果是,则使用Text={x:Bind UserControl.Value}
  • 似乎这是要走的路,但似乎我在某处缺少数据上下文,因为我在“MyProject. TestApplication.MainPage'
  • 您是否将 Value 创建为 DependencyProperty?

标签: c# xaml user-controls uwp


【解决方案1】:

您也许可以使用绑定的ElementName 部分来访问来自用户控件的值。为此,您必须为您的 UserControl 提供 x:Name,然后像这样设置您的 Binding:

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

【讨论】:

    【解决方案2】:

    确保您已将属性创建为 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}"/>
    

    (或)

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

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

    【讨论】:

    • 是的,虽然我已经将我的属性作为 DependencyProperty,但我缺少 ElementName。所以谢谢你和@jsmyth886!
    • @Nigel-Lee 你也可以使用x:Bind 并设置Mode=OneWay。我已经更新了答案。
    猜你喜欢
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多