对象引用未设置为对象的实例.Windows.forms控件导致这种情况

本文关键字:控件 情况 forms Windows 设置 对象 实例 对象引用 | 更新日期: 2023-09-27 18:37:15

我有一个例外。

我像这样为 InitializeComponent() 创建了一个尝试捕获。

try
{
    InitializeComponent();
    Auto_Complete();
}
catch(Exception ex)
{
    System.Windows.Forms.MessageBox.Show(ex.Message);
}

然后我得到一个异常,说"对象引用未设置为对象的实例。

我正在寻找错误的原因。

然后我发现错误是由于我在 xaml 中添加的控件造成的。

xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
            <WindowsFormsHost Margin="272,10,396,42" Width="240">
                <wf:TextBox x:Name="txtAutoProductCode" AutoCompleteMode="SuggestAppend" AutoCompleteSource="CustomSource" />
            </WindowsFormsHost>

这是我添加到 xaml 中的 windows.forms 控件以实现自动完成功能。

但这个例外使它变得困难。

我创建了一个自动完成()函数并连接了文本框:

    void Auto_Complete()
    {
        txtAutoProductCode.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        txtAutoProductCode.AutoCompleteSource = AutoCompleteSource.CustomSource;
        AutoCompleteStringCollection coll = new AutoCompleteStringCollection();
        SqlCeCommand com = new SqlCeCommand("SELECT ProductCode FROM Category_Master(CategoryName)", con);
        SqlCeDataReader dr;
        try
        {
            dr = com.ExecuteReader();
            while (dr.Read())
            {
                string aProduct = dr.GetString(0);
                coll.Add(aProduct);
            }
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message, System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        txtAutoProductCode.AutoCompleteCustomSource = coll;
    }
    public MainWindow()
    {
        try
        {
            InitializeComponent();
            Auto_Complete();
        }
        catch(Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.ToString());
        }
    }

这是例外

        System.Windows.Markup.XamlParseException was unhandled
  HResult=-2146233087
  Message='Initialization of 'Billing.MainWindow' threw an exception.' Line number '6' and line position '9'.
  Source=PresentationFramework
  LineNumber=6
  LinePosition=9
  StackTrace:
       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.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
       at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
       at System.Windows.Application.DoStartup()
       at System.Windows.Application.<.ctor>b__1(Object unused)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.DispatcherOperation.InvokeImpl()
       at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.ProcessQueue()
       at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at Billing.App.Main() in c:'Users'kamalmohan'Documents'Visual Studio 2012'Projects'Billing'Billing'obj'Debug'App.g.cs:line 0
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.InvalidOperationException
       HResult=-2146233079
       Message=Cannot have nested BeginInit calls on the same instance.
       Source=PresentationFramework
       StackTrace:
        at System.Windows.FrameworkElement.BeginInit()
        at MS.Internal.Xaml.Runtime.ClrObjectRuntime.InitializationGuard(XamlType xamlType, Object obj, Boolean begin)
       InnerException: 

对象引用未设置为对象的实例.Windows.forms控件导致这种情况

这可能有助于解决它,以便您准确找出问题所在

XAMLParseException 是 WPF 中引发的常见异常。不幸 这不是很有帮助。

为了帮助找出真正的错误是什么,您可以启用异常 在Visual Studio中更早地报告。默认组合键为 按 Ctrl + Alt + E。从那里,选中所有框。

现在,代码中引发的异常将在 调试器。

https://stackoverflow.com/a/9045411/427684

相关文章: