[英]Exception while setting DataContext
我創建了一個自定義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:
但是,正確繪制了自定義控件。 那么,我該如何解決呢? 這是關鍵問題嗎?
您的班級是PageHeaderControl
但您的依賴項道具PageHeaderControl
其ElevationPageHeaderControl
注冊為所有者。
我發現了我的錯誤。 這是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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.