设置DataContext时出现异常

时间:2014-04-22 16:29:38

标签: c# xaml user-controls windows-phone

我创建了一个自定义UserControl,它公开了一些DependencyProperties,如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: 

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

2 个答案:

答案 0 :(得分:0)

您的课程为PageHeaderControl,但您的相关道具已在ElevationPageHeaderControl注册为其所有者..?

答案 1 :(得分:0)

我发现了自己的错误。它是HeaderTitleForeground的类型,所以我只是从string更改为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;
}
}