如何将Command绑定到TreeView的SelectedItemChanged事件

时间:2012-12-12 05:18:49

标签: wpf treeview command selecteditemchanged

有Treeview控件。

 <TreeView Name="ProductsHierarchy" FontFamily="Arial"  
                          Background="White" Margin="2" 
                          FontSize="12" SelectedItemChanged ="ProductsHierarchy_SelectedItemChanged">

有没有办法绑定树视图的SelectedItemChanged事件的命令,避免事件处理程序后面的代码?

1 个答案:

答案 0 :(得分:2)

尝试MVVM Toolkit's EventToCommand

“内置”(来自Blend)方法是使用Interactivity

<TreeView Name="ProductsHierarchy" FontFamily="Arial"  
                          Background="White" Margin="2" 
                          FontSize="12" SelectedItemChanged ="ProductsHierarchy_SelectedItemChanged">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectedItemChanged">
            <i:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}" CommandParameter="argument"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TreeView>

您必须包含名称空间:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

此处的缺点是您无法访问EventArgs。这是solution(它是波兰语,但代码示例几乎不言自明)。