gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:07:08 26 4
gpt4 key购买 nike

编辑

这困扰了我将近一年。我会更新答案并增加赏金。

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

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()));
...
}

Figure是所有图形的基类:

public abstract class Figure { ... }

public class LineFigure : Figure { ... }
public class XGridFigure : Figure { ... }
public class YGridFigure : Figure { ... }
...

现在查看下面的屏幕截图以了解问题所在:有时(在其他地方对 xaml 进行更改后)设计师会为此疯狂并停止渲染整个窗口,抛出异常,而代码编译和运行没有问题 。我可以关闭此 xaml(设计器)并再次打开它以使问题消失。但它总是会再次出现。

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


老问题

丑陋的情况。

我有 2 UserControl .中都手作控Graph用来。 Graph有属性(property)Figures指定 List<Figure> .有几十个数字有Figure作为基础。

合一UserControl它工作正常,在其他方面抛出异常

The specified value cannot be assigned to the collection. The following type was expected: "Figure".

而且我看不出可能导致问题的区别。


这是一张有问题的截图


这是一个正在工作的

尽管项目编译和运行出错,但如果我需要对有问题的 UserControl 进行修改,然后它不显示任何内容(显示“无效标记”)。图几乎相同,都是8仅显示一个 UserControl 的错误.

我该怎么办?如何解决此类错误?我(完全)排除了 Graph 的任何问题因为它运行没有任何问题并且它可以毫无问题地用于另一个 UserControl . Visual Studio 设计器问题?使用适用于 Windows 桌面的 2013 Express。

最佳答案

事实上,视觉设计器无法识别来自 Figure 的继承。 .一种解决方案是使用 IList 作为接口(interface)类型:

    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>()));

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

关于c# - 无法将指定的值分配给集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26606280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com