.NET Core 3 和 System.Windows.Shapes.Rectangle 和 XamlReader.Parse

.NET Core 3 and System.Windows.Shapes.Rectangle and XamlReader.Parse

XamlReader.Parse 一个 XML 字符串中,将其转换为 FlowDocument 我收到以下错误:

System.Windows.Markup.XamlParseException: ''The invocation of the constructor on type 'System.Windows.Shapes.Rectangle' that matches the specified binding constraints threw an exception.'

<Rectangle Stroke="#FF000000" StrokeThickness="3" Width="Auto" Height="3" Margin="0,0,0,0" />

代码如下:

public FlowDocument ConvertToFlowDocument(string data)
{
    var x = XamlReader.Parse(data);
    return (FlowDocument)x;
}

我应该注意到错误是在 var x = XamlReader.Parse(data) 上而不是演员表上。

在 Core 3 中应该使用 Rectangle 以外的东西吗?我应该使用 XamlReader.Parse 以外的东西吗?

编辑:忘记补充说我正在将其转换为 FlowDocument

edit2: 添加了将字符串转换为 FlowDocument 的函数

好的,花了我一些时间但弄清楚了问题所在。所以事实证明错误消息有点误导。实际问题是由于使用上述方法的进程是另一个线程。尽管 Rectangle 不是 UI 的一部分,但它的行为就像它一样。为了绕过它,我不得不调用它

Application.Current.Dispatcher.Invoke((Action)delegate 
{
   //Code that uses ConvertToFlowDocument() method
}

如果有人能向我解释为什么那会很棒。