WPF provides the ability to create templated items for controls such as the list and grid.
These item templates allow any WPF controls including labels, text areas and buttons. My problem was knowing how to create code that responds to the clicks of these buttons. Wasn’t terribly obvious to me.
Here’s an example:
<DataTemplate x:Key="SomeListItemTemplate">
<StackPanel>
<TextBlock Text="{Binding Subject}" Width="188" Height="45.277"/>
<Button x:Name="cmdDeleteItem" Width="59" Height="21.277" Content="Delete" >
</StackPanel>
</DataTemplate>
The trick appears to be to create “CommandBindings”. These are an input mechanism in WPF that allows developers to define commands centrally and have them processed by the one piece of logic.
It appears this isn’t supported visually in Expression Blend unfortunately.
In order to solve my problem I had to do four things.
Firstly I defined a Window.CommandBindings section in my xaml file
<Window.CommandBindings>
<CommandBinding Command="local:MyCommands.DeleteItem" Executed="OnDeleteItem" />
</Window.CommandBindings>
(For this to work, add the ‘xmlns:local=”clr-namespace:MyProject” ‘ attribute against the Window Tag)
Secondly I created a class to host my custom command:
Public Class MyCommands
Public Shared DeleteItem As New RoutedCommand("DeleteItem", GetType(MyTasksWPF.Main))
End Class
Thirdly I created the “OnDeleteItem” method to receive my event:
Public Sub OnDeleteItem(ByVal sender As Object, ByVal args As ExecutedRoutedEventArgs)
System.Windows.MessageBox.Show("So you wanted to delete " & CStr(args.Parameter) & " punk? Well didja?")
End Sub
Finally I updated the button definition to specify the command I defined:
<Button x:Name="cmdDeleteItem" Width="59" Height="21.277" Content="Delete"
Command="local:MyCommands.DeleteItem" CommandParameter="{Binding Id}"/>
Find the SDK docummentation on the subject here:
http://www.eggheadcafe.com/software/aspnet/29895215/commandbindings-in-blend.aspx
A full example demonstrating types of using CommandBinding:
http://adoguy.com/2007/03/28/WPF_Command_Example.aspx