TL;DR: 将
{StaticResource SomePage}
绑定到 DependencyProperty
类型的 Page
会产生错误 Microsoft.VisualStudio.XSurface.Wpf.Page is not a valid value for property...
长版
我正在尝试创建一个需要注意
Page
的自定义按钮。所以我用 DependencyProperty
制作了一个自定义控件,如下所示:
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));
}
然后我尝试在某个窗口(xaml)中使用它:
<controls:MyButton AssociatedPage="{StaticResource HomePage}"
Content="Home" />
其中
HomePage
定义在同一窗口中:
<Window.Resources>
<local:HomePage x:Key="HomePage" />
</Window.Resources>
并且
HomePage.xaml
存在并编译(没有什么奇怪的)。
我收到的错误是
Microsoft.VisualStudio.XSurface.Wpf.Page is not a valid value for property 'AssociatedPage'
。我意识到这与System.Windows.Controls.Page
不一样......它来自哪里?我怎样才能使我的示例起作用?
任何帮助表示赞赏!
确保您的命名空间正确。尽管他们共享“Page”这个名字,但他们是两个不同的类别。如果你想确保它正确,你可以在你的依赖属性声明中完整地声明它。
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(Microsoft.VisualStudio.XSurface.Wpf.Page), typeof(MyButton));
}