I’m using Silverlight, but I’d be interested in a WPF answer as well
I have a list that is databound to an linked list of “Favorites”. Each favorite contains a name and a phone number.
The list is bound to a DataTemplate that describes the graphical aspects. In the this template is a button – Dial. When you click on that button I want the Dial() method of the Favorite to be called. Right now the Dial method of the page/window is called.
If this is not possible is there a way I can get the Favorite to somehow be attached to the Button? such that I know which Favorite was associated with the button press?
the below XAML does not work, Text=”{Binding Name}” works great as it binds to the Name property on the Favorite, but Click=”{Binding Dial}” does not call Dial() on the Favorite.
<DataTemplate x:Key="DataTemplate1">
<StackPanel d:DesignWidth="633" Orientation="Horizontal" Height="93">
<Button x:Name="DialButton" Content="Edit" Click="{Binding Dial}"/>
<TextBlock x:Name="TextBlock" TextWrapping="Wrap" Text="{Binding Name}" FontSize="64" Height="Auto" FontFamily="Segoe WP SemiLight"/>
</StackPanel>
</DataTemplate>
So it should go:
Then you will receive the data object as the command parameter. In this scenario you must provide a Property that is called
Dialand returns anICommand-implementation. If the property is not available on your data-object but on the main class (code-behind), you must look for it within the binding, use for this theRelativeSourcekeyword.Another way is to make a click handler. In the click handler you can cast the sender to a Button (or FrameworkElement) and then get the data object from the DataContext. I assume you tried to create such a solution.
The markup must be as follows:
The main difference is, that I removed the binding from the Click-Event and registered an event-handler.
A third solution would be, to register a handler in the code behind for the
Button.ClickEvent. The principle is similiar as in the second example.I don’t know silverlight very well. Perhaps there are the things a little bit other.