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

浪尽此生 提交于 2019-11-30 05:43:22

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/14279236/how-to-expose-a-dependencyproperty-of-a-control-nested-in-a-usercontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!