Tuesday, May 27, 2008

[Silverlight] XamlParseException when setting IsChecked flag in XAML

Alrighty, today I made a basic debug log to dump messages and test timings to. I wanted to setup a checkbox on my application to toggle the visibility [and to toggle off the logging/testing] of this debug panel... but when doing so I kept running into the exception:
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in System.Windows.dll

Additional information: AG_E_PARSER_BAD_PROPERTY_VALUE [Line: 33 Position: 206]

My checkbox had two event handlers set up on them... one for Checked and one for Unchecked. These functions would toggle the visibility of the debug log. THIS is what I had done wrong however... I had also set in my XAML the IsChecked flag equal to true.

What this essentially did then, was call the event handler I had setup for Checked. Given that this event call was actually made before the entire page was loaded, I received an error when trying to toggle the visibility of the debug log which was not actually loaded into the DOM yet!

Thus here is my recommendation:
Never EVER set the IsChecked flag of a checkbox element in the XAML code itself, since there is a good chance that whatever elements you wish to command are not properly injected into the DOM yet.

After the page is initialized then add the line "[checkboxname].IsChecked = true" in the code behind... as this will guarantee that the DOM has been fully structured.

No comments: