简体   繁体   中英

WPF change value of a child inside UserControl

I need to change a value from MainWindow of a Control inside my CustomControl . So lets say I want to change the Labels Content inside UserControl MyControl from MainWindow.xaml .

Example:

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

And in MainWindow.xaml: <MyUserControl x:Name="TestControl" />

Now how can I access Label.Content from Xaml Designer in MainWindow.xaml?

I didn't find anything out there, so hopefully someone knows how to do that.

Thanks a lot

Expose a custom Property in your UserControl, like below

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);
        }
    }
}

In xaml of MainWindow

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

Added the Following to your UserControl

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

Have the User Control Implement INotifyPropertyChanged

Add a Property to the user control like this

   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

Update the Label to Bind from that Property

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

Then in your MainWindow you can change the property accourdingly

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

Then your code behind can also reference that property

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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