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

eYe*_*eYe 7 wpf xaml user-controls properties

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

    <UserControl>   
      <Button x:Name="_OkButton" Content="OK"/>
      <DockPanel >
        <Image/>
        <TextBlock x:Name="_DialogTextBox" />
      </DockPanel>
    </UserControl>
Run Code Online (Sandbox Code Playgroud)

如何在UserControl中公开TextBlock的Image和Text属性的Source属性?

d.m*_*ada 10

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

Image Source DependencyProperty会自动设置内Image时,它被更新控制的来源.同样,Text DependencyProperty也将设置Text内部TextBlock控件.

这是设置:

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);
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

每当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>
Run Code Online (Sandbox Code Playgroud)

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


mga*_*ant 5

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

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

为了在xaml中进行绑定,下面是一个示例:

<Image Source="{Binding YourProperty, RelativeSource={RelativeSource FindAncestor, AncestorType=YourUserControl}}/>
Run Code Online (Sandbox Code Playgroud)