Note that there are some explanatory texts on larger screens.

plurals
  1. POSetting CommandTarget to selected control in a TabControl
    text
    copied!<p>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. </p> <p><strong>The question:</strong> 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.</p> <p>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).</p> <pre><code>&lt;Button Command="ApplicationCommands.Save" CommandTarget="{Binding ElementName=nestedControl}"&gt;Save&lt;/Button&gt; &lt;TabControl x:Name="tabControl"&gt; &lt;TabControl.Items&gt; &lt;TabItem Header="Header1"&gt;Item 1&lt;/TabItem&gt; &lt;TabItem Header="Header2"&gt;Item 2&lt;/TabItem&gt; &lt;TabItem Header="Header3"&gt;Item 3&lt;/TabItem&gt; &lt;/TabControl.Items&gt; &lt;TabControl.ContentTemplate&gt; &lt;DataTemplate&gt; &lt;CommandTest:NestedControl Name="nestedControl"/&gt; &lt;/DataTemplate&gt; &lt;/TabControl.ContentTemplate&gt; &lt;/TabControl&gt; </code></pre> <p>I tested the code by replacing the complete tabcontrol with only one single NestedControl, and then the command button just works.</p> <p>To be complete, here is the code of NestedControl:</p> <pre><code>&lt;UserControl x:Class="CommandTest.NestedControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Grid&gt; &lt;Label x:Name="label" Content="Not saved"/&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>And code behind:</p> <pre><code>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"; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload