views:

27

answers:

1

I am looking at the following xaml:

   <Grid x:Name="LayoutRoot" Background="White">
        <Button Content="Say Hello..." VerticalAlignment="Center" 
                HorizontalAlignment="Center" 
                my:ButtonService.Command="{Binding Path=SayHello}"
                my:ButtonService.CommandParameter="Bob"/>
    </Grid>

I would like to understand how the command gets bound with no code behind. [my:] points to a dll that defines a [ButtonService] static class which in turn defines [CommandProperty] as a DependencyProperty.

I expected this to be part of the code behind while in fact it is in its own class – ButtonService.

Can someone explain to me how (and why) does it work?

The full code is here:

Thank you in advnace.

+2  A: 

The ButtonService class will have a special form of Dependency property called an "AttachedProperty". When a value is assigned to this property the callback defined by the meta data for this dependency property will be executed.

Its this callback code in the ButtonService class which will do all the wiring up to the Button click event and the CanExecuteChanged event of the supplied ICommand value.

The whole point of this "Command" pattern is to avoid placing code in the code-behind. Code to perform some processing and to determine when such processing can be done is pushed back into the data object (often refered to as the "ViewModel") being bound. The purpose is to create a more testable code since its much easier to test code that has no UI.

Note that if you are working with Silverlight 4 then Command and CommandParameter are now implemented by Button so there is not need of this service in SL 4.

AnthonyWJones
Thank you AnthonyWJones – you are right about the rewiring of the click, but I still do not understand how can one place, in the middle of the XAML portion of the button’s declarations, this ‘my:ServiceButton.Command’ which is not part of the button.
furd