Adding a button to a datatemplate and calling its click event

I am trying to create a WPF application (using C # .net) in which I want to add a button inside a ListBox.

Here is the data template that I posted in the resource dictionary

<DataTemplate x:Key="MYTemplate"> <StackPanel Margin="4"> <DockPanel> <TextBlock Text="ISBN No:" DockPanel.Dock="Left" Margin="5,0,10,0" Foreground="AliceBlue" /> <TextBlock Text=" " /> <TextBlock Text="{Binding ISBN}" Foreground="LimeGreen" FontWeight="Bold" /> </DockPanel> <DockPanel> <TextBlock Text="Book Name:" DockPanel.Dock="Left" Margin="5,0,10,0" Foreground="AliceBlue"/> <TextBlock Text=" " /> <TextBlock Text="{Binding BookName}" Foreground="LimeGreen" FontWeight="Bold" /> </DockPanel > <DockPanel > <TextBlock Text="Publisher Name:" DockPanel.Dock="Left" Margin="5,0,10,0" Foreground="AliceBlue" /> <TextBlock Text=" " /> <TextBlock Text="{Binding PublisherName}" Foreground="LimeGreen" FontWeight="Bold" /> </DockPanel> <DockPanel> <Button Name="MyButton" Content="Click Me"> </Button> </DockPanel> </StackPanel> </DataTemplate> 

How to add click event to button tag in above template? Also, where should I put the method that will be called when the button is clicked.

+4
source share
1 answer

Nilesh

you must use button binding to the command. For example, if your data item is defined as follows:

 public class MyItem : ViewModelBase { public MyItem() { ClickMeCommand = new RelayCommand(ClickMe); } private void ClickMe() { Debug.WriteLine("I was clicked"); } public string ISBN { get; set; } public string BookName { get; set; } public string PublisherName { get; set; } public ICommand ClickMeCommand { get; set; } } 

Then it will call the ClickMe method.

 <DockPanel> <Button Content="Click Me" Command="{Binding ClickMeCommand}" /> </DockPanel> 

Or you can put this command in the parent view model:

 public class MainViewModel : ViewModelBase { public IEnumerable<MyItem> Items { get; private set; } /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { Items = new List<MyItem> { new MyItem{ ISBN = "ISBN", BookName = "Book", PublisherName = "Publisher"} }; ClickMeCommand = new RelayCommand<MyItem>(ClickMe); } private void ClickMe(MyItem item) { Debug.WriteLine(string.Format("This book was clicked: {0}", item.BookName)); } public ICommand ClickMeCommand { get; set; } 

}

and snap to it

 <DockPanel> <Button Content="Click Me" CommandParameter="{Binding}" Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}}, Path=DataContext.ClickMeCommand}" /> </DockPanel> 

Note that the code above uses the MVVM indicator, and I assume that you have

  <ListBox ItemTemplate="{StaticResource MyTemplate}" ItemsSource="{Binding Items}"/> 
+11
source

Source: https://habr.com/ru/post/1395888/


All Articles