接口/抽象的 XAML 集合“无法创建实例”
我在 ViewModel 中有一个 ObservableCollectionINode
是一个接口。
View XAML 就像:
<Windows x:Class="XXX.Window1"
xmlns:vw="clr-namespace:XXX.Views"
xmlns:vm="clr-namespace:XXX.ViewModels"
xmlns:n="clr-namespace:XXX.Models.Nodes"
... />
...
<vm:MyView>
<vw:MyView.DataContext>
<vm:MyViewModel>
<vm:ComponentViewModel.Nodes>
<n:MyNode /> <--- PROBLEM HERE
<n:MyNode />
</vm:ComponentViewModel.Nodes>
</vm:MyViewModel>
</vw:MyView.DataContext>
</vm:MyView>
...
现在这在运行时有效,但在设计时间窗口中不起作用,显示: 无法创建“MyNode”类型的实例
知道如何解决这个问题吗?
interface INode
{
string Name { get; set; }
string Status { get; }
}
abstract class Node : INode
{
public string Name { get; set; }
public abstract string Status { get; }
public override int GetHashCode()
{
unchecked
{
return Name.GetHashCode(); // <--- PROBLEM WAS HERE, Name = null
}
}
}
class MyNode : Node
{
public override NodeStatus Status { get { return "test"; } }
}
I have in the ViewModel an ObservableCollection<INode>
where INode
is an interface.
The View XAML is like:
<Windows x:Class="XXX.Window1"
xmlns:vw="clr-namespace:XXX.Views"
xmlns:vm="clr-namespace:XXX.ViewModels"
xmlns:n="clr-namespace:XXX.Models.Nodes"
... />
...
<vm:MyView>
<vw:MyView.DataContext>
<vm:MyViewModel>
<vm:ComponentViewModel.Nodes>
<n:MyNode /> <--- PROBLEM HERE
<n:MyNode />
</vm:ComponentViewModel.Nodes>
</vm:MyViewModel>
</vw:MyView.DataContext>
</vm:MyView>
...
Now this works at runtime, but not in the design time window which shows:
Could not create an instance of type 'MyNode'
Any idea how to solve this?
interface INode
{
string Name { get; set; }
string Status { get; }
}
abstract class Node : INode
{
public string Name { get; set; }
public abstract string Status { get; }
public override int GetHashCode()
{
unchecked
{
return Name.GetHashCode(); // <--- PROBLEM WAS HERE, Name = null
}
}
}
class MyNode : Node
{
public override NodeStatus Status { get { return "test"; } }
}
每个案例似乎都是独一无二的。以下是我在解决该问题后了解到的内容:不仅构造函数中的异常会生成该错误消息。如果某些系统方法(例如
GetHashCode()
)抛出异常,它会显示相同的消息(有时仅在设计时)。其他人可能对设计时流程有更多技巧或更多见解。
Each case seem to be unique. Here's what I learned after solving it: Not only an exception in the constructor can generate that error message. If some system methods like
GetHashCode()
throw and exception, it'll display that same message (some times at design-time only).Other people may have more tips or more insight VS design-time flow.