Adding buttons via code behind using XamlReader.Parse Causes exception

时间:2018-06-04 17:25:28

标签: c# xaml exception

I am writing a program that reads in a group of files. Inside of these files is a line of XAML to add a button. I don't know anything about the button setup other than it is properly formed XAML.

When I use XamlRead.Parse it throws the exception" : Exception thrown: 'System.Windows.Markup.XamlParseException' in PresentationFramework.dll Additional information: 'Cannot create unknown type 'Button'.' Line number '1' and line position '2'.

For testing my input file looks like so:

<Button Width="250" Height="50" Content="Button From Test File" Background="Yellow"/>

And my code looks like:

... 
    int start = filedata.IndexOf("<Button");
    if (start >=0)
    {
        string btnData = filedata.Substring(start, filedata.IndexOf("/>") - start + 2);                    

        Button cmdButton = CreateButton(btnData);
    }
...

private Button CreateButton(string ButtonXML)
{
     Button newButn = new Button();

     newButn = (Button)System.Windows.Markup.XamlReader.Parse(ButtonXML);

     return NewButn;
}

When I put the Button XAML into my mainwindow.xaml project file it shows the button fine.

Why is it giving me the exception?

1 个答案:

答案 0 :(得分:0)

哈克能够指出我正确的方向。我想保持输入文件中的代码干净,所以我决定在传入时对字符串进行一些调整。创建按钮功能现在看起来像这样:

private Button CreateButton(string ButtonXML)
{
    Button newButn = new Button();
    ButtonXML = ButtonXML.Replace("<Button", @"<Button xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");

    newButn = (Button)System.Windows.Markup.XamlReader.Parse(ButtonXML);

    return NewButn;
}