C# 如何在设计时避免 XAML 代码中的“对象引用未设置为对象的实例”异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17701545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Howto avoid a "object reference not set to an instance of an object" exception in XAML code while design time?
提问by Kimbo
I have a problem with a wpf usercontrol which is of my own devising.
The problem is that i get a object reference not set to an instance of an object
exception in XAML code while design time, when I implement the usercontrol in my program.
我自己设计的 wpf 用户控件有问题。问题是我object reference not set to an instance of an object
在设计时在 XAML 代码中遇到异常,当我在我的程序中实现用户控件时。
How can i fix or suppress the exeption?
我怎样才能修复或抑制例外?
EDIT 1
编辑 1
The designer show me following information:
设计师向我展示了以下信息:
at Microsoft.Expression.Platform.InstanceBuilders.InstanceBuilderOperations.InstantiateType(Type type, Boolean supportInternal) at Microsoft.Expression.Platform.InstanceBuilders.ClrObjectInstanceBuilder.InstantiateTargetType(IInstanceBuilderContext context, ViewNode viewNode) at Microsoft.Expression.Platform.InstanceBuilders.ClrObjectInstanceBuilder.Instantiate(IInstanceBuilderContext context, ViewNode viewNode) at Microsoft.Expression.WpfPlatform.InstanceBuilders.FrameworkElementInstanceBuilder.Instantiate(IInstanceBuilderContext context, ViewNode viewNode) at Microsoft.Expression.WpfPlatform.InstanceBuilders.UserControlInstanceBuilder.Instantiate(IInstanceBuilderContext context, ViewNode viewNode) at Microsoft.Expression.Platform.InstanceBuilders.ViewNodeManager.CreateInstance(IInstanceBuilder builder, ViewNode viewNode)
在 Microsoft.Expression.Platform.InstanceBuilders.InstanceBuilderOperations.InstantiateType(Type type, Boolean supportInternal) 在 Microsoft.Expression.Platform.InstanceBuilders.ClrObjectInstanceBuilder.InstantiateTargetType(IInstanceBuilderContext context, ViewNode viewNode) 在 Microsoft.Expression.Platform.InstanceBuilders.ClrObjectInstanceBuilder.Instantiate (IInstanceBuilderContext context, ViewNode viewNode) at Microsoft.Expression.WpfPlatform.InstanceBuilders.FrameworkElementInstanceBuilder.Instantiate(IInstanceBuilderContext context, ViewNode viewNode) at Microsoft.Expression.WpfPlatform.InstanceBuilders.UserControlInstanceBuilder.Instantiate(IInstanceBuilderContext context, ViewNode viewNode) at Microsoft.Expression。 Platform.InstanceBuilders.ViewNodeManager.CreateInstance(IInstanceBuilder 构建器,ViewNode viewNode)
I think they are not really helpful...
我认为他们并没有真正的帮助...
回答by Bob Horn
You could do something like this:
你可以这样做:
using System.ComponentModel;
using System.Windows;
/// <summary>
/// WPF Design Mode helper class.
/// </summary>
public static class DesignMode
{
private static bool? _isInDesignMode;
/// <summary>
/// Gets a value indicating whether the control is in design mode (running in Blend
/// or Visual Studio).
/// </summary>
public static bool IsInDesignMode
{
get
{
if (!_isInDesignMode.HasValue)
{
var prop = DesignerProperties.IsInDesignModeProperty;
_isInDesignMode
= (bool)DependencyPropertyDescriptor
.FromProperty(prop, typeof(FrameworkElement))
.Metadata.DefaultValue;
}
return _isInDesignMode.Value;
}
}
}
Then, as the first line in the constructor of your view (or view model), you can do something like this:
然后,作为视图(或视图模型)构造函数中的第一行,您可以执行以下操作:
if (DesignMode.IsInDesignMode) { return; }
That way your code will only run when you're actually running it.
这样你的代码只会在你实际运行时运行。
回答by Shumii
Whatever is happening in your constructor is throwing an exception during design time. I had same problem - I just put a try catch around the problematic code - in my case I was calling ServiceLocator.Current as I am using an IoC container. But there is no container during design time. So I wrapped in a try catch to suppress the error and it worked. Not the best solution... but its a solution.
构造函数中发生的任何事情都会在设计时引发异常。我遇到了同样的问题 - 我只是在有问题的代码周围放了一个 try catch - 在我的情况下,我在使用 IoC 容器时调用了 ServiceLocator.Current。但是在设计时没有容器。所以我用 try catch 包裹来抑制错误并且它起作用了。不是最好的解决方案......但它是一个解决方案。
回答by Gareth
I tend to use the LicenseManager
class in System.ComponentModel
to avoid my ViewModels throwing nasty errors at designtime. For example:
我倾向于使用LicenseManager
该类System.ComponentModel
来避免我的 ViewModel 在设计时抛出令人讨厌的错误。例如:
public MyViewModel()
{
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
// Do runtime stuff
}
}
回答by aherocalledFrog
Tweaking @BobHorn's example, I got this to work for me:
调整@BobHorn 的例子,我得到了这个为我工作:
public class ViewModel
{
public ViewModel()
{
if (!IsInDesignMode)
{
//Constructor code here...
}
}
public bool IsInDesignMode
{
get
{
var prop = DesignerProperties.IsInDesignModeProperty;
return (bool)DependencyPropertyDescriptor
.FromProperty(prop, typeof(FrameworkElement))
.Metadata.DefaultValue;
}
}
}
Though using his exact suggestion for the constructor
虽然使用他对构造函数的确切建议
public Main()
{
if (IsInDesignMode) { return; }
//Constructor code here...
}
Did also work for me, I just prefer not short-circuiting my methods with extra return statements. I would have up-voted his answer, don't have the rep yet.
也对我有用,我只是不想用额外的 return 语句来短路我的方法。我会赞成他的回答,还没有代表。
回答by Dark Knight
I had the similar problem. You just need to go to Tools> Options> XAML Designerand enable the option
我有类似的问题。您只需要转到“工具”>“选项”>“XAML 设计器”并启用该选项
"Run project code in XAML designer".
“在 XAML 设计器中运行项目代码”。
Finally restart Visual Studio. I hope this will help.
最后重启Visual Studio。我希望这将有所帮助。
回答by Lirrik
If you have 'Object reference not set to an instance of an object' in XAML, but your application compiles and runs fine, you will usually find out that its cause is something in a constructor that can't be resolved at design time.
如果您在 XAML 中有“未将对象引用设置为对象的实例”,但您的应用程序编译并运行良好,您通常会发现其原因是在设计时无法解决的构造函数中。
You can just click the "Disable project code" button located on the bottom of your designer view and Visual Studio designer will stop trying to construct an instance to provide design time data view.
您只需单击位于设计器视图底部的“禁用项目代码”按钮,Visual Studio 设计器将停止尝试构建实例以提供设计时数据视图。
See herefor detailed information and screenshots.
有关详细信息和屏幕截图,请参见此处。
回答by Paulustrious
VS 2017 UWP:
VS 2017 UWP:
if (false == Windows.ApplicationModel.DesignMode.DesignModeEnabled)
{
// Anything in here need not be OK at Design time in Visual Studio
}
回答by Jagger
In you "partial class" of XAML, if you can see " [XamlCompilation(XamlCompilationOptions.Compile)]
",
just remove the line, and then try build again.
在 XAML 的“部分类”中,如果可以看到“ [XamlCompilation(XamlCompilationOptions.Compile)]
”,只需删除该行,然后再次尝试构建。
回答by Alan
If someone else comes here, I had inadvertently dragged my MainWindow.xaml file to a sub folder. Dragging it back fixed the problem.
如果其他人来到这里,我无意中将 MainWindow.xaml 文件拖到了子文件夹中。把它拖回来解决了这个问题。
回答by Raj
When you work on a WIndow/UserControl in the designer it "runs" the parameterless constructor. If you have code in there which is reliant on something usually provided by some other piece of code then this often causes a problem. The designer doesn't run any other code first so dependencies usually provided elsewhere can be missing and cause errors. Suppressing these is a matter of detecting whether that code is running in the designer or not. It's often most convenient to just return out the constructor:
当您在设计器中处理 WIndow/UserControl 时,它会“运行”无参数构造函数。如果您的代码依赖于通常由其他代码段提供的某些内容,那么这通常会导致问题。设计器不会首先运行任何其他代码,因此通常在其他地方提供的依赖项可能会丢失并导致错误。抑制这些是检测该代码是否在设计器中运行的问题。返回构造函数通常是最方便的:
public MainWindow()
{
InitializeComponent();
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
return;
//code
}
More in detail https://social.technet.microsoft.com/wiki/contents/articles/29874.aspx?Redirected=true
更详细的https://social.technet.microsoft.com/wiki/contents/articles/29874.aspx?Redirected=true