我有一些 Xaml 对象的字符串表示形式,并且我想构建控件。我正在使用XamlReader.Parse函数来执行此操作。对于像 Button 这样的简单控件,它有一个不带任何参数的默认构造函数,这样可以很好地工作:
var buttonStr = "<Button xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">Text</Button>";
var button = (Button)XamlReader.Parse(buttonStr);
然而,当我尝试这样做时,例如a 行程控制失败。首先尝试一个简单的空描边:
var strokeStr = "<Stroke xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"></Stroke>";
var stroke = (Stroke)XamlReader.Parse(strokeStr);
这给出了错误:
无法创建“System.Windows.Ink.Stroke”类型的对象。 CreateInstance 失败,这可能是由于没有“System.Windows.Ink.Stroke”的公共默认构造函数造成的。
在 Stroke 的定义中,我发现它至少需要构造一个 StylusPointsCollection。我认为这就是错误告诉我的内容,尽管有点假设这将由 XamlReader 处理。尝试使用 StylusPoints 转换 Stroke 的 Xaml 会产生相同的错误:
var strokeStr =
"<Stroke xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" +
"<Stroke.StylusPoints>" +
"<StylusPoint X=\"100\" Y=\"100\" />" +
"<StylusPoint X=\"200\" Y=\"200\" />" +
"</Stroke.StylusPoints>" +
"</Stroke>";
var stroke = (Stroke) XamlReader.Parse(strokeStr);
我究竟做错了什么?如何告诉 XamlReader 如何正确创建 Stroke?
它是 XAML 语言的一个“功能”,它是声明性的,并且不了解有关构造函数的任何信息。
人们使用对象数据提供者在 XAML 中“翻译”并包装没有无参数构造函数的类的实例(它是对于数据绑定也很有用).
在您的情况下,XAML 应该大致如下所示:
<ObjectDataProvider ObjectType="Stroke">
<ObjectDataProvider.ConstructorParameters>
<StylusPointsCollection>
<StylusPoint X="100" Y="100"/>
<StylusPoint X="200" Y="200"/>
</StylusPointsCollection>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
代码应该是:
var stroke = (Stroke) ((ObjectDataProvider)XamlReader.Parse(xamlStr)).Data;
HTH.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)