簡體   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