试图将整个Window绑定到Usercontrol

时间:2019-03-19 12:28:50

标签: c# wpf data-binding dependency-properties

我正在尝试将我的整个窗口绑定到基础用户控件,以使该用户控件控制父窗口的行为。例如,我想从userControl关闭父窗口。我想创建一个可在其他窗口中重用的自定义TitleBar。我尝试使用

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

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

2 个答案:

答案 0 :(得分:0)

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

TZ=Etc/UTC

答案 1 :(得分:0)

感谢所有帮助。 我不知道什么是行不通的。我清除了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}}}" />