如何在 WPF 中将内部控件的 属性 公开给其父 UserControl

How to expose internal control's property to its parent UserControl in WPF

我有一个 DialogPrompt UserControl,它将有一个 Image 和一个 TextBlock。这是模板:

    <UserControl>   
      <Button x:Name="_OkButton" Content="OK"/>
      <DockPanel >
        <Image/>
        <TextBlock x:Name="_DialogTextBox" />
      </DockPanel>
    </UserControl>

如何在我的 UserControl 中公开图像的源 属性 和文本块的文本 属性?

在后面的代码中,添加 2 个 DependencyProperties 并将它们绑定到图像源和 TextBlock 文本。

这里是关于如何使用和创建依赖属性的教程: http://www.wpftutorial.net/dependencyproperties.html

对于 xaml 中的绑定,这里有一个示例:

<Image Source="{Binding YourProperty, RelativeSource={RelativeSource FindAncestor, AncestorType=YourUserControl}}/>

我会创建两个 DependencyProperties,一个用于 Text,一个用于 Image Source

Image Source DependencyProperty 将在更新时自动设置内部 Image 控件的源。同样,Text DependencyProperty 也将设置内部 TextBlock 控件的 Text

设置如下:

public partial class MyUserControl : UserControl
{
    #region ImageSource
    public static readonly DependencyProperty ImageSourceProperty = 
        DependencyProperty.Register
        ( 
            "ImageSource", 
            typeof(Uri),
            typeof(MyUserControl), 
            new FrameworkPropertyMetadata(new PropertyChangedCallback(OnImageSourceChanged))
        );

    public Uri ImageSource
    {
        get { return (Uri)GetValue(ImageSourceProperty); }
        set { SetValue(ImageSourceProperty, value); }
    }
    #endregion ImageSource

    #region Text
    public static readonly DependencyProperty TextProperty = 
        DependencyProperty.Register
        ( 
            "Text", 
            typeof(string),
            typeof(MyUserControl), 
            new FrameworkPropertyMetadata("")
        );

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
    #endregion Text

    public MyUserControl()
    {
        InitializeComponent();
    }

    private static void OnImageSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var myUserControl = sender as MyUserControl;
        if (myUserControl != null)
        {
            myUserControl.ImageSource.Source = new BitmapImage((Uri) e.NewValue);
        }
    }
} 

每当 Image Source 更改时,这将自动更新内部 Image 控件的源代码。注意,我们需要在这里做一些转换,因为 Image 控件本身使用 ImageSource 类型。

XAML 可以更新为:

   <UserControl x:Name="ControlName">   
      <Button x:Name = "OkButton" Content="OK"/>
      <DockPanel >
        <Image x:Name = "MyImage" />
        <TextBlock x:Name = "DialogTextBox" Text="{Binding ElementName=ControlName, Path=Text}"/>
      </DockPanel>
    </UserControl>

在这里,内部 TextBlock 控件简单地绑定到父级(主 UserControl)的 Text DependencyProperty