使用XamlReader用于没有默认构造函数的控件
-
22-09-2019 - |
题
我有一些XAML对象的字符串表示,我想构建控件。我正在使用 xamlreader.parse 功能来执行此操作。对于一个简单的控件,例如具有默认构造函数不使用任何参数的按钮,这很好:
var buttonStr = "<Button xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">Text</Button>";
var button = (Button)XamlReader.Parse(buttonStr);
但是,当我尝试做到这一点时,例如中风控制失败。首先尝试一个简单的空冲程:
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”的公共默认构造函数而引起的。
在中风的定义中,我看到它至少需要构造styluspointscollection。我认为这是错误告诉我的,尽管有点假设这将由Xamlreader处理。试图在其中使用styluspoints转换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如何正确创建中风?
解决方案
这是XAML语言的“功能”,它是声明性的,对构造函数一无所知。
人们使用 ObjectDataProvider 在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。
不隶属于 StackOverflow