XAML:访问用户控件内的控件

我有这样的userControl:

    

我在另一个XAML中使用这个userControl,如下所示:

  

现在我如何在这个XAML中访问名为Text的textBlock并更改他的文本(在Windows Phone 8中)? 像这样的东西:

   ` 

谢谢。

我找到了解决方案。

       

在C#代码中:

 public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof (String), typeof(MyButton),null); public String Title { get { return (String)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } 

然后在任何地方你可以像这样使用:

  

你不能直接这样做。 这有两种选择。

解决方案1:使用ViewModel

使用视图模型类来存储需要在自定义控件中显示的属性。

 class MyButtonViewModel { public string Text { get;set; } } 

MyButton.xaml:

  

MainWindow.xaml

     

这使用MVVM模式。 如果您从未使用过,请参阅使用Model-View-ViewModel设计模式的WPF应用程序 。

解决方案2:使用CustomControl

CustomControl替换UserControl 。 在这种情况下, Text可以是依赖属性,因此您可以编写。

  

这要复杂得多。 请参见如何创建WPF自定义控件 。

选择哪个?

如果您打算在几个不同的项目中使用您的控件,并且您需要能够更改控件的外观,请选择UserControl

否则,请转到ViewModel并最终在项目的剩余部分中应用MVVM模式。

要实现此任务,一种解决方案可能是将依赖属性声明为您的Control (后面似乎称为“MyButton”)代码:

  public string ButtonText { get { return (string )this.GetValue(ButtonTextProperty); } set { this.SetValue(ButtonTextProperty, value); } } public static readonly DependencyProperty ButtonTextProperty = DependencyProperty.Register( "ButtonText", typeof(string), typeof(MyButton),new PropertyMetadata(false)); 

然后你必须将它绑定到你的xaml代码:

   ... // some xaml code      

最后,您可以使用“MyButton” Control