Using XamlReader for controls that does not have a default constructor

后端 未结 1 1527
执笔经年
执笔经年 2021-01-21 02:21

I have some string representations of Xaml objects, and I want to build the controls. I\'m using the XamlReader.Parse function to do this. For a simple control such as Button th

相关标签:
1条回答
  • 2021-01-21 03:07

    It's a "feature" of the XAML language, it is declarative and doesn't know anything about constructors.

    People use ObjectDataProvider in XAML to "translate" and wrap instances of classes that do not have a parameterless constructor (it's also useful for data binding).

    In your case the XAML should look approximately like this:

    <ObjectDataProvider ObjectType="Stroke">
        <ObjectDataProvider.ConstructorParameters>
            <StylusPointsCollection>
                <StylusPoint X="100" Y="100"/>
                <StylusPoint X="200" Y="200"/>
            </StylusPointsCollection>
        </ObjectDataProvider.ConstructorParameters>
    </ObjectDataProvider>
    

    And the code should be:

    var stroke = (Stroke) ((ObjectDataProvider)XamlReader.Parse(xamlStr)).Data;
    

    HTH.

    0 讨论(0)
提交回复
热议问题