尝试将整个 Window 绑定到用户控件

Trying to bind whole Window to Usercontrol

我试图将我的整个 window 绑定到底层用户控件,让该用户控件控制 parent window 行为。例如,我想从 userControl 中关闭 parent window。我想创建一个可以在其他 windows 中重用的自定义标题栏。我试过使用

<views:TitlebarUserCtrl BoundWindow="{Binding ElementName=Window1, Mode=OneWay}" ></views:TitlebarUserCtrl>    

.

public static readonly DependencyProperty BoundCurrentWindow = DependencyProperty.Register("BoundWindow", typeof(Window), typeof(TitlebarUserCtrl), new UIPropertyMetadata(""));
public Window BoundWindow
{
    get
    {
        return (Window)GetValue(BoundCurrentWindow);
    }
    set
    {
        SetValue(BoundCurrentWindow, value);
    }
}

但我只得到一个错误。有什么建议吗?

您可以使用寻找 Window-Type-control 的相对来源绑定到您的 window:

<views:TitlebarUserCtrl BoundWindow="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/>

感谢大家的帮助。 我不知道什么不起作用。我清除了 obj 文件夹,错误消失了。编辑:我将 UIPropertyMetadata("") 设置为 null - 这似乎解决了它。

正确代码如下:

C#
public static readonly DependencyProperty BoundCurrentWindow = DependencyProperty.Register("BoundWindowProperty", typeof(Window), typeof(TitlebarUserCtrl), null);
public Window BoundWindowProperty
    {
        get
        {
            return (Window)GetValue(BoundCurrentWindow);
        }
        set
        {
            SetValue(BoundCurrentWindow, value);
        }
    }

WPF
<views:TitlebarUserCtrl BoundWindowProperty="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" />