2

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?

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.