I have a WPF window with several buttons and a tabcontrol with a tab for each "document" the user is working on. Tabcontrol uses a DataTemplate to visualize data in an ItemSource tabcontrol.
Question: If one of the buttons is pressed, the command must be executed in the control that displays the document on the active tab, but I have no idea why the CommandTarget should be installed. I tried {Binding ElementName = nameOfControlInDataTemplate}, but this clearly does not work.
I tried to make my problem more abstract with the following code (ItemSource and Document objects are not saved, but the idea is 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>
, tabcontrol NestedControl, .
, 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>
:
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";
}
}