1

I am retrieving a xaml string from a database and constructing a xaml canvas.

The call

 loadedCanvas = (Canvas)System.Windows.Markup.XamlReader.Parse(xamlTemplate);

works fine from the UI thread. When I try to do the same thing from a BackgroundWorker thread I get a XamlParseException with the message 'Cannot create unkown type Canvas' pointing to the first Canvas tag.

The xaml is the same in both cases.

I get the feeling that I'm missing something blindingly obvious.

1 Answer 1

3

I 'm not sure why you are getting the specific error message (which is misleading), but you cannot load XAML from a non-UI thread; even if you could, you would then be unable to use them from your UI thread because WPF controls have thread affinity.

The reason you cannot load from non-UI (technically the restriction is "non-STA thread") is that UI elements require the current thread to be STA for marshalling purposes and will throw an exception to that effect if you are currently inside a MTA thread. The managed thread pool, which BackgroundWorker uses, has only MTA threads.

TL;DR: You need to do this from within your UI thread.

1
  • Thanks for the answer; it makes perfect sense. It was blindingly obvious after all ;)
    – fran
    May 10, 2012 at 6:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.