2016-12-14 85 views
0

孩子的WPF变化值我需要从主窗口一个控制的改变我CustomControl内的值。 所以可以说,我想从MainWindow.xaml改变标签内用户控件MyControl内容内用户控件

例子:

<UserControl x:Class="XXXXX.MyUserControl" 
. 
. 
. 
> 
    <Grid> 
     <Label x:Name="TestLabel"/> 
    </Grid> 
</UserControl> 

而且在MainWindow.xaml: <MyUserControl x:Name="TestControl" />

现在,我怎么访问Label.Content从XAML设计在MainWindow.xaml?

我没有找到任何东西,所以希望有人知道如何做到这一点。

非常感谢

+0

那么你的代码是什么样的? –

+0

您是否尝试让用户控件使用与主窗口相同的数据上下文? – Bryan

+0

@Bryan这将如何? –

回答

0

添加了以下到您的用户控件

<UserControl x:Class="XXXXX.MyUserControl" 
    DataContext="{Binding RelativeSource={RelativeSource Self}}" 
. 
. 
> 

让用户控制执行INotifyPropertyChanged

属性添加到用户控件这样

Private _LabelText As String 
    Public Property LabelText() As String 
     Get 
      Return _LabelText 
     End Get 
     Set(ByVal value As String) 
      _LabelText = value 
      OnPropertyChanged("LabelText") 
     End Set 
    End Property 

更新标签以绑定该属性

<Label x:Name="TestLabel" Content="{Binding Path=LabelText}"/> 

然后在你的主窗口,您可以更改属性accourdingly

<MyUserControl x:Name="TestControl" LabelText="Testing" /> 

那么后面你的代码也可以引用财产

+0

嗯,是的,如果我想设置单个或几个属性的标签,但如果我想设置一百个,该怎么办?用这种方法,我将不得不创建100个新的属性,这将是完全超大的。更好的解决方案是直接绑定到MainWindow.Xaml –

+0

@DanielDirtyNativeMartin的标签属性,您要求的完全删除用户控件会更有意义。但是如果你想保持用户控制并且能够将值绑定到控件上,我认为这是你想要的。 – Bryan

+0

由于可重用性,如果它可以放在UserControl中并且尽可能简单,它将非常有用。是否没有真正的可能性直接访问该UserControl内的Label?这样你就可以完全访问该标签的所有属性。 –

1

公开自定义属性,你的用户控件,如下面

public partial class MyUserControl : UserControl 
{ 
    public MyUserControl() 
    { 
     InitializeComponent(); 

     var dpd = DependencyPropertyDescriptor.FromProperty(LabelContentProperty, typeof(MyUserControl)); 
     dpd.AddValueChanged(this, (sender, args) => 
     { 
      _label.Content = this.LabelContent;   
     }); 
    } 

    public static readonly DependencyProperty LabelContentProperty = DependencyProperty.Register("LabelContent", typeof(string), typeof(MyUserControl)); 

    public string LabelContent 
    { 
     get 
     { 
      return GetValue(LabelContentProperty) as string; 
     } 
     set 
     { 
      SetValue(LabelContentProperty, value); 
     } 
    } 
} 

在MainWindow的xaml中

<MyUserControl x:Name="TestControl" LabelContent="Some Content"/>