繁体   English   中英

用户控件内子项的WPF更改值

[英]WPF change value of a child inside UserControl

我需要在CustomControl中Control的 MainWindow更改一个值。 所以可以说我想从MainWindow.xaml更改UserControl MyControl中Labels 内容

例:

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

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

现在如何在MainWindow.xaml中从Xaml Designer访问Label.Content?

我在那里什么都没找到,所以希望有人知道该怎么做。

非常感谢

在用户控件中公开自定义属性,如下所示

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

将以下内容添加到您的UserControl中

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

然后在您的MainWindow中,您可以相应地更改属性

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

然后您后面的代码也可以引用该属性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM