Search code examples
c#wpfdata-bindingdependency-properties

Trying to bind whole Window to Usercontrol


I'm trying to bind my whole window to a underlying usercontrol to let that usercontrol control parent window behaviour. For example i would like to close the parent window from the userControl. I want to create a custom TitleBar that i can reuse in other windows. I have tried using

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

But i only get a error. Any suggestions?


Solution

  • Thanks for all help. I don't know what was not working. I cleared the obj folder and the error dissapeared. Edit: and I set UIPropertyMetadata("") to null - that seemed to fix it.

    Here is the correct code:

    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}}}" />