SideSky
SideSky

Reputation: 343

WPF MVVM - Binding Command not found because of ItemsSource

I have a custom TabControl with an ItemsSource binded to it. Inside the ItemTemplate is a Button which Command I want to bind to a RelayCommand from my DataContext (ViewModel).

The Problem is, that the application is looking for the Command inside my ItemsSource Item.

<TabControl ItemsSource="{Binding ViewModel.TabItems,UpdateSourceTrigger=PropertyChanged}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <DockPanel>
                <!-- The "Header" is from the "TabItems" Model -->
                <TextBlock Text="{Binding Header}" />
                <!-- I want to bind this Command outside the "TabItems" Model -->
                <Button Command="{Binding ViewModel.CounterIncrementCommand, Mode=OneWay}"/>
            </DockPanel>
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <TextBox>Test</TextBox>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

I get the Binding Failures:

Upvotes: 0

Views: 64

Answers (1)

SideSky
SideSky

Reputation: 343

Okay, I found it out. With this I can set the DataContext of the Button to the same one of the Window/Page:

<Button DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Page}}}" Command="{Binding ViewModel.CounterIncrementCommand}"/>

Upvotes: 0

Related Questions