views:

96

answers:

1

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"&gt;
    <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";
    }
}
A: 

I don't know exactly how CommandTarget works, but binding to the active tab in a TabControl is done with something like this:

"{Binding ElementName=tabControl,Path=SelectedItem}"

(SelectedItem is the current active tab)

EDIT:

More information about CommandTarget can be found here: http://stackoverflow.com/questions/1015851/setting-command-target-in-xaml

EDIT 2:

Deleted my initial answer since it was not an answer to the question.

Tendlon
My apologies, I got the impression (I don't know from where) that you were using a Model-View-ViewModel pattern. I'll edit in a link to more information about CommandTarget
Tendlon
"{Binding ElementName=tabControl,Path=SelectedItem}" would bind the command to the selected TabItem, I've also tried SelectedContent, but that binds the command to the string within the TabItem ("Item 1", etc), but it should go to the NestedControl. I think we getting warm here ;)
Bart