Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get SelectedItem of WPF Treeview

I am making a WPF application with MVVM Light, and I have the following 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.

Thanks.

like image 323
TSM Avatar asked Nov 24 '25 01:11

TSM


1 Answers

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

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

like image 120
agugglez Avatar answered Nov 26 '25 16:11

agugglez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!