Reputation:
In my XAML
, I have defined a button as such:
<DataTemplate x:Key="ItemTemplate">
<WrapPanel Orientation="Vertical" Width="Auto">
<Button Width="200" Height="300" Click="SelectMovie_Click" >
<Button.Template>
<ControlTemplate >
<Image Source="{Binding image}"/>
</ControlTemplate>
</Button.Template>
<i:Interaction.Behaviors>
<local:UniqueNameBehavior ID="{Binding id}"/>
</i:Interaction.Behaviors>
</Button>
<TextBlock Text="{Binding title}" HorizontalAlignment="Center"/>
</WrapPanel>
</DataTemplate>
I use the Behaviour
to dynamically assign a name to my button.
public class UniqueNameBehavior : Behavior<FrameworkElement>
{
public UniqueNameBehavior() : base() { }
public String ID
{
get { return (String)this.GetValue(IDProperty); }
set { this.SetValue(IDProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
//Assign unique name to the associated element
AssociatedObject.Name = "movie" + ID;
}
public static readonly DependencyProperty IDProperty = DependencyProperty.Register(
"ID", typeof(String),
typeof(UniqueNameBehavior));
}
When this button is clicked, I would like to pass this Name
to my ViewModel
.
This is my Behind-Code
private void SelectMovie_Click(object sender, RoutedEventArgs e)
{
// _moviePanelVM is an instance of my ViewModel
_moviePanelVM.GetSelectedMovieDetails();
}
So I understand I could retrieve the button name here and pass it to the ViewModel
but I feel this might not be the right way to do this if using the MVVM
model.
Could anyone please suggest as to how I might achieve this the correct way?
Thank you for your help.
Upvotes: 0
Views: 1849
Reputation: 414
Use command parameters in XAML file. This is simple sintax to pass object with button "CommandParameter={Binding senderObject}" add this at the end of the button tag.
Access the same in the
private void SelectMovie_Click(object sender, RoutedEventArgs e)
{
String buttonId = sender as String;
// _moviePanelVM is an instance of my ViewModel
_moviePanelVM.GetSelectedMovieDetails();
}
Upvotes: 0
Reputation: 2203
You could add a Command in your ViewModel: For example the Commands Section here could help: Implementing the MVVM Pattern Using the Prism Library 5.0 for WPF .
And add a parametrized Command with the help of the Prism library and as the parameter you commit the Name of your button (Internet is full of help). And bind the command to your button.
Upvotes: 1