wpf 如何将命令绑定到 TreeView 的 SelectedItemChanged 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13833279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:34:22  来源:igfitidea点击:

How to bind a Command to SelectedItemChanged event of a TreeView

wpftreeviewcommandselecteditemchanged

提问by user1874589

There is a Treeview Control.

有一个树视图控件。

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

Is there a way to bind a command for SelectedItemChanged event of the treeview, avoiding the code behind event handler?

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

回答by amnezjak

Try MVVM Toolkit's EventToCommand.

试试MVVM 工具包的 EventToCommand

"Built-in" (from Blend) approach is to use Interactivity

“内置”(来自 Blend)方法是使用交互性

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

You must include namespace:

您必须包含命名空间:

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

The disadvantage here is that you have no access to EventArgs. Here's the solution(it's in Polish, but code samples are pretty much self-explanatory).

这里的缺点是您无法访问EventArgs. 这是解决方案(它是波兰语,但代码示例几乎不言自明)。