Zirui Wang
Zirui Wang

Reputation: 259

Binding a TabItem in WPF

In WPF, a button can be bound to a command.

<Button Command="{Binding DoSomething}">Click me!</Button>

Now I want to do the same to a TabItem:

<TabItem Header="A little tab" ???="{Binding DoSomething}">...</TabItem>

What should ??? be? Or is there another way to do it?

Upvotes: 2

Views: 1461

Answers (1)

Lupu Silviu
Lupu Silviu

Reputation: 1165

It depends on what do you want to achieve. TabItems have the IsSelected property

IsSelected="{Binding IsSelected}"

that can be bounded TwoWay, and can be used to signal stuff to the ViewModel.

You could also use the fact that you can override the header of the TabItem, and bound it to a command, using Interactivity.

 <TabItem TabIndex="0"
                 Tag="{Binding CurrentPrinterStatus}">
            <TabItem.Header>
                <Grid Background="Transparent">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="MouseDown">
                            <i:InvokeCommandAction Command="{Binding DoSomething}"/>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                    <TextBlock Style="{StaticResource TextBlockSelectedStyle}"
                           Text="Printers"/>
                </Grid>
            </TabItem.Header>

Other solutions are to use the SelectionChanged event of the TabControl, and that could allow you to find the ViewModel of the TabItem currently selected.

Hope this ideas atleast help you get a solution to your problem.

Upvotes: 3

Related Questions