My app allows users to put some custom XAML markup into a textbox. When my app loads I use XamlReader.Parse to load the tree. I then overwrite some Resources in my MergedDictionaries with these custom resources.
This has worked well and I can catch the XamlParseException when a user has entered invalid Xaml. The problem comes when a user types in an incorrect attribute value like the Color of a Border. If they type in Grey instead of Gray, there are no exceptions and the UI just fails to display. In fact it appears like the app has frozen.
This problem can also be replicated in the VS Designer. Just type in an incorrect Color value (ignore Intellisense). There will be no warnings in VS.
Are there any ways to catch this incorrect attribute value?
If you load DataTemplates using XamlReader (and in general) - xaml inside DataTemplate itself is not parsed until template is used for the first time (xml validation is performed still of course). So to handle that, you can do:
var dt = (DataTemplate)XamlReader.Parse("<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><TextBox Background=\"Gray\" /></DataTemplate>"); // < template with invalid color
try {
dt.LoadContent(); // this will parse template content
}
catch (XamlParseException ex) {
// notify user xaml is invalid
}