How to open an internal control property for your parent UserControl in WPF

I have a UserControl DialogPrompt that will have an image and a text block. Here is the template:

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

How to open the Source property of the Image and Text properties for a TextBlock inside my UserControl?

+4
source share
2 answers

I would create two DependencyProperties, one for Textand one for Image Source.

Image Source DependencyPropertywill automatically install the internal control source Imagewhenever it is updated. Similarly, it Text DependencyPropertywill install an Textinternal control TextBlock.

Here is the setup:

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 Text DependencyProperty ( UserControl).

+8

2 DependencyProperties TextBlock.

: http://www.wpftutorial.net/dependencyproperties.html

xaml, :

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

All Articles