CurlyFro
CurlyFro

Reputation: 1882

how to get TabHeader on trigger

i have a tabcontrol. i'm trying to pass the tabcontrol as a parameter to figure out the selected tab item so i can get the tab header name. Binding this doesn't seem to work. ideas?

<TabControl Background="#FFF9F9F9" Height="650">
    <i:Interaction.Triggers>
        <i:EventTrigger  EventName="SelectionChanged">
            <n:ExecuteCommandAction Command="{Binding UpdateTabCommand}" Parameter="{Binding this}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>

in my viewmodel constructor i have:

_updateTabCommand = new ActionCommand< TabControl>(UpdateTab);

private method:

public void UpdateTab(TabControl tabControl)
{
    var tabItem = (TabItem)tabControl.SelectedItem;

Upvotes: 0

Views: 493

Answers (2)

Anvaka
Anvaka

Reputation: 15823

First of all there is no such thing as {Binding this} in WPF. If you want to refer to the element on which you are setting Binding use RelativeSource binding with mode set to Self.

Second observation. Passing UI elements to ViewModel smells badly (impacts testability, increases code coupling and most likely the class will end up violating more good design principles). The fix is really simple: just bind TabControl.SelectedItem to the field on ViewModel.

Upvotes: 0

decyclone
decyclone

Reputation: 30830

1) Use ElementName binding.

Example:

<TabControl Background="#FFF9F9F9"
            Height="650"
            Name="TabControl1">
    <i:Interaction.Triggers>
        <i:EventTrigger  EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding UpdateTabCommand}"
                                    CommandParameter="{Binding ElementName=TabControl1}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TabControl>

2) Use FindAncestor binding:

Example:

<i:Interaction.Triggers>
    <i:EventTrigger  EventName="SelectionChanged">
        <i:InvokeCommandAction Command="{Binding UpdateTabCommand}"
                                CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TabControl}}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

Upvotes: 2

Related Questions