Silverlight Tip: RadioButton/CheckBox Binding ClickMode

No doubt that Binding in Silverlight is a powerful feature. There are few caveats when considering RadioButton or CheckBox like controls.
The following code snippet is a common scenario where a RadioButton or CheckBox can be used with data binding.

 <ItemsControl>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <RadioButton Content="{Binding ItemName}" IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
 </ItemsControl>

Let’s consider a situation where you want to show a list of options to choose from for the user. And whenever a selection is made, you want to perform a certain kind of actions.
In that case you may change the code something similar to,

   <ItemsControl>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <RadioButton Content="{Binding ItemName}" IsChecked="{Binding IsSelected, Mode=TwoWay}"
                                 Checked="RadioButton_Checked"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
   </ItemsControl>

And in the RadioButton’s Checked event handler you may want to do some kind of action based on the IsSelected value. Now if you try to read the value of IsSelected in the event handler, you’ll still see it as False.

This is because the value of the binding property will be updated only after completing the cycle of UnChecked and Checked events.
To make sure of the binding property is updated, you can use the property ClickMode, exists for both RadioButton and CheckBox.

ClickMode takes the following three values,

Now let’s Change the Xaml as follows,

<ItemsControl.ItemTemplate>
                <DataTemplate>
                    <RadioButton Content="{Binding ItemName}" IsChecked="{Binding IsSelected, Mode=TwoWay}"
                                 Click="RadioButton_Click" ClickMode="Release"/>
                </DataTemplate>
</ItemsControl.ItemTemplate>

Note that we have changed the event handler to Click from Checked and set the ClickMode to Release.

Now if you read IsSelected in the Click handler, you’ll get the exact value.

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *