如何在触发器上获取Tab Header

时间:2010-12-29 17:39:55

标签: wpf xaml binding

我有一个tabcontrol。我正在尝试将tabcontrol作为参数传递出来以找出所选标签项,以便我可以获取标签标题名称。绑定这似乎不起作用。想法?

<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>

在我的viewmodel构造函数中我有:

_updateTabCommand = new ActionCommand< TabControl>(UpdateTab);

私人方法:

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

2 个答案:

答案 0 :(得分:2)

1)使用ElementName绑定。

实施例

<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)使用FindAncestor绑定:

实施例

<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>

答案 1 :(得分:0)

首先,WPF中没有{Binding this}这样的东西。如果要引用要设置绑定的元素,请使用RelativeSource绑定,并将模式设置为Self

第二次观察。将UI元素传递给ViewModel会很难闻(影响可测试性,增加代码耦合,最有可能的是,类最终会违反更多good design principles)。修复非常简单:只需将TabControl.SelectedItem绑定到ViewModel上的字段。

相关问题