Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Expose a DependencyProperty of a Control nested in a UserControl?

I'm trying to bind an Image down from a Window into a UserControl 'Display' thats inside a UserControl 'DisplayHandler'. Display has a DependancyProperty 'DisplayImage'. This is Similar to this, but their answers didn't help with my problem.

DisplayHandler also should have the Property 'DisplayImage' and pass down the Binding to Display. But Visual Studio doesn't allow me to register a DependancyProperty with the same name twice. So I tried to not register it twice but only to reuse it:

window

<my:DisplayHandler DisplayImage=
    "{Binding ElementName=ImageList, Path=SelectedItem.Image}" />

DisplayHandler

xaml

<my:Display x:Name="display1"/>

cs

public static readonly DependencyProperty DisplayImageProperty =
    myHWindowCtrl.DisplayImageProperty.AddOwner(typeof(DisplayHandler));

public HImage DisplayImage {
    get { return (HImage)GetValue(DisplayImageProperty); }
    set { SetValue(DisplayImageProperty, value); }
}
public HImage DisplayImage /*alternative*/ {
    get { return (HImage)display1.GetValue(Display.DisplayImageProperty); }
    set { display1.SetValue(Display.DisplayImageProperty, value); }
}

**neither of the 2 properties worked out.*

Display

public HImage DisplayImage {
    get { return (HImage)GetValue(DisplayImageProperty); }
    set { SetValue(DisplayImageProperty, value); }
}
public static readonly DependencyProperty DisplayImageProperty =
    DependencyProperty.Register("DisplayImage", typeof(HImage), typeof(Display));

I have been thinking a Control goes up the Tree and looks for its Property if its own Value is not defined. ->reference

So it should work somehow...

I made some attempts with Templating and A ContentPresenter because that worked for the ImageList(ImageList also contains the Display), but I couldn't get it to bind the value like for an ListBoxItem.

like image 467
Daniel Bammer Avatar asked Oct 06 '22 09:10

Daniel Bammer


1 Answers

The AddOwner solution should be working, but you have to add a PropertyChangedCallback that updates the embedded control.

public partial class DisplayHandler : UserControl
{
    public static readonly DependencyProperty DisplayImageProperty =
        Display.DisplayImageProperty.AddOwner(typeof(DisplayHandler),
            new FrameworkPropertyMetadata(DisplayImagePropertyChanged));

    public HImage DisplayImage
    {
        get { return (Image)GetValue(DisplayImageProperty); }
        set { SetValue(DisplayImageProperty, value); }
    }

    private static void DisplayImagePropertyChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var dh = obj as DisplayHandler;
        dh.display1.DisplayImage = e.NewValue as HImage;
    }
}
like image 62
Clemens Avatar answered Oct 10 '22 03:10

Clemens