Wednesday, June 10, 2009

Why value converter never executes.

For debug XAML in WPF, we do not have considerable approaches to choose. The most useful way we use frequently is to add value converter and check the output window in VS. however, the text in output window is so large. We seem to need more time to find what we are expect. but in other circumstance, we add a value converter but never executes. In this topic, let talk about this scenario in practice.

Let’s consider the following simple code snippet, in the Window.resource section, we define the a SolidColorBrush instance and bind its Color property to the Label element. When we run the application, we find the value converter never executes. This is because the Label loads before the value converter executes. In order to verify this, we can add two breakpoints at the Loaded event handler of Label and System.Windows.Media.SolidColorBrush.SolidColorBrush(), run the application and see the CallStack window in Visual Studio. We can find the sequence of execution.

Code:

<Window.Resources>
<
local:SelectionBackgroundConverter x:Key
="SelectionBackgroundConverter"/>
<
SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey
}"
Color="{Binding Path=Background,ElementName=label, Converter={StaticResource SelectionBackgroundConverter
}}" />
</
Window.Resources
>
<
StackPanel
>
<
Label Content="Label" Name="label" Background="Green" Loaded
="OnLoaded" />
<
ListBox x:Name="LB" HorizontalAlignment="Stretch" VerticalAlignment
="Stretch" />
</
StackPanel>


Hope this helps.



Thanks.


0 comments:

Post a Comment