繁体   English   中英

如何公开嵌套在UserControl中的控件的DependencyProperty?

[英]How to Expose a DependencyProperty of a Control nested in a UserControl?

我正在尝试将一个图像从一个窗口绑定到UserControl'DisplayHandler'中的UserControl'Display'。 Display具有DependancyProperty'DisplayImage'。 这是类似这样的,但他们的回答并没有与我的问题有所帮助。

DisplayHandler还应具有属性'DisplayImage'并将Binding传递给Display。 但Visual Studio不允许我两次注册具有相同名称的DependancyProperty。 所以我试着不再注册两次,只是为了重用它:

窗口

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

**两个物业都没有成功。*

显示

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

我一直在想,如果没有定义自己的值,Control会上升树并查找其属性。 - >参考

所以它应该以某种方式工作......

我使用Templating和ContentPresenter进行了一些尝试,因为它适用于ImageList(ImageList也包含Display),但是我无法像ListBoxItem那样绑定值。

AddOwner解决方案应该正常工作,但您必须添加一个更新嵌入式控件的PropertyChangedCallback

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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