Setting CommandTarget to selected control in a TabControl
- by Bart
I have a WPF window with a few buttons and a tabcontrol having a tab for each 'document' the user is working on. The tabcontrol uses a DataTemplate to render the data in ItemSource of the tabcontrol.
The question: If one of the buttons is clicked, the command should be executed on the control rendering the document in the active tab, but I've no idea what I should set CommandTarget to. I tried {Binding ElementName=nameOfControlInDataTemplate} but that obviously doesn't work.
I tried to make my problem a bit more abstract with the following code (no ItemSource and Document objects, but the idea is still the same).
<Button Command="ApplicationCommands.Save" CommandTarget="{Binding ElementName=nestedControl}">Save</Button>
<TabControl x:Name="tabControl">
<TabControl.Items>
<TabItem Header="Header1">Item 1</TabItem>
<TabItem Header="Header2">Item 2</TabItem>
<TabItem Header="Header3">Item 3</TabItem>
</TabControl.Items>
<TabControl.ContentTemplate>
<DataTemplate>
<CommandTest:NestedControl Name="nestedControl"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
I tested the code by replacing the complete tabcontrol with only one single NestedControl, and then the command button just works.
To be complete, here is the code of NestedControl:
<UserControl x:Class="CommandTest.NestedControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Label x:Name="label" Content="Not saved"/>
</Grid>
</UserControl>
And code behind:
public partial class NestedControl : UserControl {
public NestedControl() {
CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, CommandBinding_Executed));
InitializeComponent();
}
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {
label.Content = "Saved";
}
}