设置DataContext时出现异常

本文关键字:异常 DataContext 设置 | 更新日期: 2023-09-27 17:59:19

我创建了一个自定义UserControl,它公开了一些DependencyProperty,如HeaderTitle和HeaderTitleForeground

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: 

但是,自定义控件是正确绘制的。那么,我该如何解决这个问题呢?这是一个关键问题吗?

设置DataContext时出现异常

您的类是PageHeaderControl,但您的依赖项道具已向ElevationPageHeaderControl注册为其所有者。。?

我发现了我的错误。这是HeaderTitleForeground的类型,所以我只是从字符串改为SolidColorBrush,并将SolidColorBruch(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;
}
}