# Thursday, 15 April 2010

While I guess I understand why this would be a problem, I don’t understand why it worked before…

If I want to create a style for a button, let’s say with a red background, I might create a brush resource that defines my special color of red, then reference that brush in a style resource like so

<SolidColorBrush x:Key="TheBrush">
    <SolidColorBrush.Color>Red</SolidColorBrush.Color>
</SolidColorBrush>            
<Style x:Key="RedButton" TargetType="Button">
    <Setter Property="Background" Value="{StaticResource TheBrush}"/>
</Style>

That works just fine.  I get a red button like this

image

If the two resources are in the opposite order

<Style x:Key="RedButton" TargetType="Button">
    <Setter Property="Background" Value="{StaticResource TheBrush}"/>
</Style>
<SolidColorBrush x:Key="TheBrush">
    <SolidColorBrush.Color>Red</SolidColorBrush.Color>
</SolidColorBrush> 

then at runtime I’m going to end up with an exception because the resource “TheBrush” can’t be found.  Hmmm.  I suppose that makes sense if we imagine the XAML processor instancing objects as it comes to them in the XZML file.  It would try to instance “RedButton” and not be able to create the static reference to “TheBrush” because that object hasn’t been instanced yet.

If I happen to apply that style some something in my XAML

<Button 
    Style="{StaticResource RedButton}" 
    Content="Red Button" Height="23"
    Click="button1_Click" />

I’ll get a compile error.  OK.  If, however, the reference to “RedButton” is in something like a DataTemplate that doesn’t get applied until runtime, then I get a rather jarring runtime exception instead. 

Again, I suppose this behavior makes sense given my theoretical model of the XAML processor (though it smacks of C++-ishness).  What doesn’t make sense is why it worked just fine in the RC, and just recompiling in the release of VS 2010 I now get runtime exceptions.  Something obviously changed in the way resources are loaded and/or referenced at runtime.

Thursday, 15 April 2010 13:02:03 (Pacific Daylight Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  |