简体   繁体   中英

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.

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM