3

我有一些 Xaml 对象的字符串表示形式,我想构建控件。我正在使用XamlReader.Parse函数来执行此操作。对于一个简单的控件,例如具有默认构造函数的 Button 不带任何参数,这可以正常工作:

var buttonStr = "<Button xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">Text</Button>";
var button = (Button)XamlReader.Parse(buttonStr); 

但是,当我尝试对 Stroke 控件执行此操作时,它会失败。首先尝试一个简单的空笔画:

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 转换 Xaml 的 Stroke 会产生相同的错误:

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?

4

1 回答 1

3

它是 XAML 语言的“特性”,它是声明性的,对构造函数一无所知。

人们在 XAML 中使用ObjectDataProvider来“翻译”和包装没有无参数构造函数的类的实例(它对于数据绑定也很有用)。

在您的情况下,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。

于 2010-02-25T17:10:28.367 回答