C# 设置DataContext时发生异常
我创建了一个自定义UserControl,它公开了一些依赖属性,如HeaderTitle和HeaderTitleC# 设置DataContext时发生异常,c#,xaml,user-controls,windows-phone,C#,Xaml,User Controls,Windows Phone,我创建了一个自定义UserControl,它公开了一些依赖属性,如HeaderTitle和HeaderTitle public partial class PageHeaderControl : UserControl { public string HeaderTitle { get { return (string)GetValue(HeaderTitleProperty); } set { SetValue(HeaderTitlePrope
public partial class PageHeaderControl : UserControl
{
public string HeaderTitle
{
get { return (string)GetValue(HeaderTitleProperty); }
set { SetValue(HeaderTitleProperty, value); }
}
public static readonly DependencyProperty HeaderTitleProperty = DependencyProperty.Register("HeaderTitle", typeof(string), typeof(PageHeaderControl), new PropertyMetadata(""));
public string HeaderTitleForeground
{
get { return (string)GetValue(HeaderTitleForegroundProperty); }
set { SetValue(HeaderTitleForegroundProperty, value); }
}
public static readonly DependencyProperty HeaderTitleForegroundProperty = DependencyProperty.Register("HeaderTitleForeground", typeof(string), typeof(PageHeaderControl), new PropertyMetadata(""));
public PageHeaderControl()
{
InitializeComponent();
(this.Content as FrameworkElement).DataContext = this;
}
}
但当我调试我的应用程序时,它抛出了一个异常,如下所示:
System.Exception occurred
_HResult=-2146233088
_message=Error HRESULT E_FAIL has been returned from a call to a COM component.
HResult=-2146233088
Message=Error HRESULT E_FAIL has been returned from a call to a COM component.
Source=System.Windows
StackTrace:
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
InnerException:
但是,自定义控件已正确绘制。那么,我该如何解决这个问题呢?这是一个关键问题吗?您的类是
PageHeaderControl
,但您的依赖项道具已注册为其所有者。我发现了我的错误。这是HeaderTitleForeground的类型,所以我只是将字符串更改为SolidColorBrush,并将SolidColorBrush(Colors.Black)添加到PropertyMetadata。以下是UserControl的固定版本:
public partial class PageHeaderControl : UserControl
{
public string HeaderTitle
{
get { return (string)GetValue(HeaderTitleProperty); }
set { SetValue(HeaderTitleProperty, value); }
}
public static readonly DependencyProperty HeaderTitleProperty = DependencyProperty.Register("HeaderTitle", typeof(string), typeof(PageHeaderControl), new PropertyMetadata(""));
public SolidColorBrush HeaderTitleForeground
{
get { return (SolidColorBrush)GetValue(HeaderTitleForegroundProperty); }
set { SetValue(HeaderTitleForegroundProperty, value); }
}
public static readonly DependencyProperty HeaderTitleForegroundProperty = DependencyProperty.Register("HeaderTitleForeground", typeof(SolidColorBrush), typeof(PageHeaderControl), new PropertyMetadata(new SolidColorBrush(Colors.Black)));
public PageHeaderControl()
{
InitializeComponent();
(this.Content as FrameworkElement).DataContext = this;
}
}
那是个打字错误。谢谢你的评论。我刚才回答了下面的问题。