开发者

Setting CommandTarget to selected control in a TabControl

开发者 https://www.devze.com 2023-01-01 15:08 出处:网络
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

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 p开发者_Python百科artial 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";
    }
}


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: Setting Command Target in XAML

EDIT 2:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消