R – Problem with Binding Close Command to Button in a Tabcontrol datatemplate

bindingcommandprismtabcontrolwpf

I'm Using Composite Application Guidance Pattern for building my WPF application. In my Shell I have a tabcontrol which contains a region for dynamically load Views into the region. The views is loaded into new tabs in the TabControl.

  <TabControl     
      AutomationProperties.AutomationId="MainTabControl" 
      cal:RegionManager.RegionName="{x:Static inf:RegionNames.MainRegion}" 
      Width="Auto" Height="Auto" Margin="10,10,0,0" 
      HorizontalAlignment="Stretch"                            
      IsSynchronizedWithCurrentItem="True"
      ItemTemplate="{StaticResource TabItemTemplate}"
SelectionChanged="TabControl_SelectionChanged">

I have a DataTemplate "TabItemTemplate" for implementing a CloseButton. I can't figure out how to bind the button´s command in the DataTemplate to the Close Command in the presentationModel. If I bind the command to a CompositCommand, the command is executed. But then I must figure out which tab that close button was pressed and only execute closeCommand in that PresentationModel. Below is the dataTemplate.

<DataTemplate x:Key="ClosableTabItemTemplate">
            <DockPanel Width="120">
                <Button 
                    Command="inf:CloseCommands.CloseCommand"
                    Content="X"
                    Cursor="Hand"
                    DockPanel.Dock="Right"
                    Focusable="False"
                    FontFamily="Courier" 
                    FontSize="9"
                    FontWeight="Bold"  
                    Margin="0,1,0,0"
                    Padding="0"
                    VerticalContentAlignment="Bottom"
                    Width="16" Height="16" 
                    />
                <ContentPresenter 
        Content="{Binding}" 
        VerticalAlignment="Center" 
        />
            </DockPanel>
        </DataTemplate> 

Does anyone know how to solve this binding problem?

Best Answer

I had the same issue whilst learning Prism and got around it by using element binding.

<Button Content="x" Command="{Binding ElementName=Scooby, Path=Content.DataContext.CloseCommand}" />

Where Scooby is the name of my shell window and CloseCommand is a Prism DelegateCommand in the ViewModel of the Shell.

I thought I should add this here as it would demonstrate an alternate way to your solution.

Related Topic