尝试将整个Window绑定到Usercontrol

问题描述 投票:0回答:2

我正在尝试将我的整个窗口绑定到底层用户控件,以使该usercontrol控制父窗口行为。例如,我想从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);
    }
}

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

c# wpf data-binding dependency-properties
2个回答
0
投票

谢谢你的帮助。我不知道什么不起作用。我清除了obj文件夹,错误消失了。编辑:我将PropertyMetadata(“”)设置为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}}}" />

0
投票

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

<views:TitlebarUserCtrl BoundWindow="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/>
© www.soinside.com 2019 - 2024. All rights reserved.