无法将指定的值分配给集合

Sin*_*atr 5 c# wpf xaml

编辑

这让我困扰了将近一年.我会更新答案并添加赏金.

我有自定义控件,它具有依赖属性

public class Graph : Control
{
    public List<Figure> Figures
    {
        get { return (List<Figure>)GetValue(FiguresProperty); }
        set { SetValue(FiguresProperty, value); }
    }
    public static readonly DependencyProperty FiguresProperty =
        DependencyProperty.Register("Figures", typeof(List<Figure>), typeof(Graph),
        new PropertyMetadata((d, e) => ((Graph)d).InvalidateVisual()));
    ...
}
Run Code Online (Sandbox Code Playgroud)

Figure 是所有数字的基类:

public abstract class Figure { ... }

public class LineFigure : Figure { ... }
public class XGridFigure : Figure { ... }
public class YGridFigure : Figure { ... }
...
Run Code Online (Sandbox Code Playgroud)

现在看下面的截图来看问题:有时候(在其他地方对xaml进行更改之后)设计师对它疯狂并停止渲染整个窗口,抛出异常,而代码编译并运行没有问题.我可以关闭这个xaml(设计师)并再次打开它以使问题消失.但它总是重新出现.

问题:我身边有什么问题吗?缺少属性?错误的用法?我该如何解决这个问题?


老问题

丑陋的情况.

我有2个UserControl.在两个手工制作的控制Graph中使用.Graph有财产Figures来指定List<Figure>.有几十个数字Figure作为基础.

在一个UserControl它工作正常,在其他抛出异常

无法将指定的值分配给集合.预计会出现以下类型:"图".

我没有看到可能导致问题的区别.


这是一个有问题的截图


这是一个工作

尽管项目编译和运行有错误,但如果我需要修改有问题UserControl,那么它没有显示任何内容(说"无效标记").图表几乎相同,所有8错误仅显示一个UserControl.

我该怎么办?如何解决此类错误?我完全排除了(完全)任何问题,Graph因为它运行没有一个问题,它对另一个问题没有问题UserControl.Visual Studio设计师的问题?使用2013 Express for Windows Desktop.

小智 2

事实上,视觉设计师并没有认识到来自 的继承Figure。一种解决方案是使用 IList 作为接口类型:

    public IList Figures
    {
        get
        {
            return (IList)GetValue (FiguresProperty);
        }
        set
        {
            SetValue (FiguresProperty, value);
        }
    }

    public static readonly DependencyProperty FiguresProperty =
        DependencyProperty.Register ("Figures", typeof (IList), typeof (Graph), new PropertyMetadata (new List<object>()));
Run Code Online (Sandbox Code Playgroud)

这可能看起来有点奇怪(因为你放弃了类型安全性)。但仔细看看 WPF 类。他们都这样做(很可能有充分的理由)。PathFigureCollection或者 WPF 甚至创建像同时实现IList和 的集合类IList<PathFigure>