c# - WPF 用户控件初始化组件异常

标签 c# .net wpf xaml

我有一个强类型的 View 类,我的所有 UserControl 都派生自该类。它看起来或多或少像这样:

public class View<TContext> : UserControl 
{

    /// <summary>
        /// Gets or sets a value indicating whether to auto create the data context type.
        /// </summary>
    public static DependencyProperty AutoCreateDataContextProperty = DependencyProperty.Register("AutoCreateDataContext", typeof(bool), typeof(View<TContext>), new PropertyMetadata(false));
    /// <summary>
    /// Gets or sets a value indicating whether to auto create the data context type.
    /// </summary>
    /// <value>
    ///     <c>true</c> if [auto resolve data context]; otherwise, <c>false</c>.
    /// </value>
    public bool AutoCreateDataContext
    {
        get { return (bool)GetValue(AutoCreateDataContextProperty); }
        set { SetValue(AutoCreateDataContextProperty, value); }
    }

    /// <summary>
    /// Gets or sets the view model.
    /// </summary>
    /// <value>
    /// The view model.
    /// </value>
    public new TContext DataContext
    {
        get
        {
            if (AutoCreateDataContext && !DesignerProperties.GetIsInDesignMode(new ContentControl()))
            {
                base.DataContext = ServiceProvider.Current.GetService<TContext>();
            }
            return (TContext)base.DataContext;
        }
        set { base.DataContext = value; }
    }
}

关于 AutoCreateDataContext 的内容是新的......并且是我问题的根源。将其添加到 View<TContext>基类本身并没有引起任何问题...但是一旦我在派生 View 之一中将值设置为 true:

<s:View x:TypeArguments="local:PersonSearchViewModel"
    x:Class="PersonSearchView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ...
             Height="600" Width="800" Background="White" AutoCreateDataContext="True">

此 View 的InitializeComponent 引发以下异常:

System.NullReferenceException occurred
  Message=Object reference not set to an instance of an object.
  Source=PresentationFramework
  StackTrace:
       at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
       at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
       at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
       at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
       at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
       at ....

一旦我从标记中删除 AutoCreateDataContext=True,它就会再次正常工作。没有内部异常或进一步的异常细节。我该如何调试/解决这个问题?

最佳答案

我做了一些猜测,然后反汇编,发现这是 WPF 如何处理在通用 DependencyObjects 上声明的 DependencyProperties 的错误(例如我的 View<T> )。

创建了一个抽象的非泛型基类(称为 View, which View<T> now inherits from )并在那里声明了我的 DependencyProperties 。问题解决了。

我想我已经习惯了 Microsoft 的质量有多差......所以我实际上已经开始认识到此类错误的趋势。

关于c# - WPF 用户控件初始化组件异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9245734/

相关文章:

c# - WhenActivated 在 ViewModelViewHost 控件中托管的 Views 和 ViewModel 中使用时被调用两次

.net - OPC : how to write a C# Hello World client? 新手指南

.net - 下载 .NET 3.5 的 Entity Framework

c# - 与转换器的双向数据绑定(bind)不更新源

c# - 如何在后台以单声道运行exe

c# - 系统.ArgumentNullException : Value cannot be null in unit test - C#

c# - 为什么 LINQ to SQL 实体关联在插入新记录时创建新的(重复的)行?

wpf - Nhibernate 是否支持 Sybase?

c# - 将文件传输到目的地时取消文件传输

c# 如何从不受信任的服务器读取证书信息