簡體   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