In this question I asked about adding TabItems dynamically to a TabControl
the ItemsSource are from ObservableCollection<Village>..
My question is if added a button to any TabItem, this button will have the DataContext of its container TabItem, how could I implement the Click event for this button?
Add a comment
|
1 Answer
If you have added the Button to the DataTemplate, then on your Button_Click method you can easily get the 'Village' datacontext.
void Button_Click(object sender, RoutedEventArgs e)
{
Village clickedVillage = ((Button)sender).DataContext as Village;
//Do whatever you want to do with the Village
}
But again, the above solution is not the best way to go for this problem. MVVM pattern would expect a ICommand in your Village (Or its container class) and you will bind that command to the Button.Command property so there wont be any code-behind at all. Or in other words your XAML will be more cleaner and ViewModel will get more self-contained in terms of properties and actions.