How to do button command binding (by convention) in DataTemplate?

Dec 3, 2010 at 3:10 AM

I have moved the UI in my main WP7 app view into two templates (portrait and landscape) referenced by a ContentControl. Most bindings worked as is, but button bindings to methods in the viewModel no longer work. I did a quick seach here and could not find anything directly related. Anyone encounter this and have a solution? Something like CM:Bind.Model in a Binding declaration for the button? Or am I forced to go back to the Prism style commanding with DelegateCommand? Maybe facing the same visibility problem there... Thanks.

<DataTemplate x:Key="portrait">
	<Button x:Name="DecreaseTimeSignature" >
<Image Source="../Assets/Dark/" 
Height="30" Width="30"/>

<ContentControl x:Name="MainContent" ContentTemplate="{StaticResource portrait}" Content="{Binding}"/>

Dec 3, 2010 at 3:39 AM

Unfortunately, it's not possible to apply convention to a plain datatemplate because WPF/SL does not provide a hook that we can tap into to intercept the elements created by the template and apply the bindings transparently. We can do it with normal views because we control the creation of the user control, but DataTemplate element creation is completely opaque. However, you can add a small bit of xaml to the root element of the template to hook CM's convention mechanism. To do this, you would add a Model.Bind="{Binding}".

Dec 3, 2010 at 6:26 PM

Thanks, Rob. I got it working with Prism's DelegateCommand approach (good old reliable), but can try Model.Bind="{Binding}" rather easily in one of the template's root grid (temporarily remove the Commanding markup from the buttons, since the delegate calls the x:Name method anyway :)). I have one more item on my punch list for complete portrait/landscape support. This also nicely opens the door to the smaller screen size form factor that I truly hope Microsoft nix'es. That item involves a button with an image that has to be swapped out based on current theme, and I think that is a candidate for a user control, which is what I had to do with several other elements once I moved everything to data templates (so storyboards could find their targets).

Dec 3, 2010 at 7:38 PM

You could always just use Message.Attach on the button, then you don't need to bring in prism...and you get all the additional features of actions. Remember, everything that can be done with conventions can also be done explicitly.

Dec 5, 2010 at 10:14 PM

I just use the DelegateCommand.cs and Commands.cs from the Prism 3 source like I've used before, but I will look into Message.Attach after I get over this cold I'm fighting with. Thanks (sniffle).