开发者

XAML collection of interface/abstract "Could not create an instance"

I have in the ViewModel an ObservableCollection<INode> where INode is an interf开发者_如何学Goace.

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"; } }
}


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.


As far as I can see it is not a XAML problem, but happens because you are not setting the Name property. When GetHashCode is called it will fail because you are calling a method on a null reference.

Try adding your node as

<n:MyNode Name="blah" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜