WPF assign a Page to a Dependency Property

78 views Asked by At

TL;DR: Binding a {StaticResource SomePage} to a DependencyProperty of type Page gives the error Microsoft.VisualStudio.XSurface.Wpf.Page is not a valid value for property...

Long Version

I am trying to create a custom button that needs to be aware of a Page. So I made a custom control with a DependencyProperty like so:

public class MyButton : Button
{
  static MyButton() {
    DefaultStyleKeyProperty.OverrideMetadata(typeof(MyButton), new FrameworkPropertyMetadata(typeof(MyButton)));
  }

  public Page AssociatedPage {
    get { return (Page)GetValue(AssociatedPageProperty); }
    set { SetValue(AssociatedPageProperty, value); }
  }

  public static readonly DependencyProperty AssociatedPageProperty =
      DependencyProperty.Register("AssociatedPage", typeof(Page), typeof(MyButton));
}

Then I try to use it inside some window (xaml):

<controls:MyButton AssociatedPage="{StaticResource HomePage}"
                   Content="Home" />

Where HomePage is defined in the same window:

<Window.Resources>
  <local:HomePage x:Key="HomePage" />
</Window.Resources>

And HomePage.xaml exists and compiles (nothing weird there).

The error I am getting is Microsoft.VisualStudio.XSurface.Wpf.Page is not a valid value for property 'AssociatedPage'. I realize that's not the same as System.Windows.Controls.Page... where is that coming from? How can I make my example work?

Any help appreciated!

1

There are 1 answers

0
dow On BEST ANSWER

TL;DR Ignore the editor message, make sure your resource dictionaries are built as Pages and not Resources, and look elsewhere for the source of the problem.

The message Microsoft.VisualStudio.XSurface.Wpf.Page is not a valid value for property... that appears when hovering over the posted binding is an editor bug.

Changing the binding

from AssociatedPage="{StaticResource HomePage}"

to AssociatedPage="{Binding Source={StaticResource HomePage}"

made the wrongful editor message disappear.

Note that a couple of visual studio updates later, the bug manifests more rarely. When it does happen, it's always because of binding to some control or a subclass of.