获取 WPF Treeview 的 SelectedItem

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17113173/
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 09:00:38  来源:igfitidea点击:

Get SelectedItem of WPF Treeview

c#wpfmvvmmvvm-light

提问by TSM

I am making a WPF application with MVVM Light, and I have the following TreeView:

我正在使用 MVVM Light 制作 WPF 应用程序,并且我有以下 TreeView:

<TreeView x:Name="TreeView" 
                  Grid.Column="2" 
                  HorizontalAlignment="Left" Height="463.481" VerticalAlignment="Top" Width="263" 
                  ItemsSource="{Binding PackageView}" Margin="0,5.657,0,0" Grid.Row="1" Grid.RowSpan="2" Grid.ColumnSpan="2">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectedItemChanged">
                    <i:InvokeCommandAction Command="{Binding Command}" 
                    CommandParameter="SelectedItemChanged"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
            <TreeView.ItemContainerStyle>
                <Style TargetType="{x:Type TreeViewItem}">
                    <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
                    <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
                    <Setter Property="FontWeight" Value="Normal" />
                    <Style.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="FontWeight" Value="Bold" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TreeView.ItemContainerStyle>

When the selection is changed, I want to send the newly selected item as an argument to the command. Is there any way to do this? I was under the impression that you could do this with EventToCommand, but when I try to use them, it says they are no longer supported in version 4, and I can't find a suitable workaround.

When the selection is changed, I want to send the newly selected item as an argument to the command. 有没有办法做到这一点?我的印象是您可以使用 EventToCommand 来做到这一点,但是当我尝试使用它们时,它说版本 4 不再支持它们,我找不到合适的解决方法。

Thanks.

谢谢。

回答by agugglez

When you specify CommandParameter="SelectedItemChanged"you are specifying the paramater as a string.

当您指定时,CommandParameter="SelectedItemChanged"您将参数指定为string.

If you want to pass the SelectedItem as the parameter, you should do it like this: CommandParameter="{Binding ElementName=TreeView,Path=SelectedItem}".

如果你想通过的SelectedItem作为参数,你应该这样做是这样的:CommandParameter="{Binding ElementName=TreeView,Path=SelectedItem}"