C# MVVM Treeview SelectedItem Binding with ICommand. Thoughts?

时间:2017-03-22 18:45:09

标签: c# wpf xaml mvvm treeview

I've been doing a lot of research and I don't understand exaclty how to properly bind an ICommand to my TreeView item.

I have a VM that holds a Data Object.

This data object holds an ObservableCollection object of TreeNode item objects.

This TreeNode Item has properties such as Tag, IsSelected, Header and even a ContextMenu.

However I can't figure out how to bind an ICommand to a single TreeView item.

Here is my XAML of my TreeView

    <TreeView Grid.Column="0" Grid.Row="0"
              Grid.ColumnSpan="1" Grid.RowSpan="5"
              x:Name="TestPlanTreeView"
              ItemsSource="{Binding Data.TestPlanCollection}"
              dd:DragDrop.IsDragSource="True" 
              dd:DragDrop.IsDropTarget="True">

        <TreeView.ItemContainerStyle>
            <Style TargetType="TreeViewItem">
                <Setter Property="Focusable" Value="{Binding Focusable, Mode=TwoWay}"/>
                <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
                <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="FontWeight" Value="Bold"/>
                        <Setter Property="FontStyle" Value="Italic"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TreeView.ItemContainerStyle>
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Children}">
                <TextBlock Text="{Binding Header}" Margin="2">
                    <TextBlock.ContextMenu>
                        <ContextMenu ItemsSource="{Binding MenuCollection}">
                            <ContextMenu.ItemContainerStyle>
                                <Style TargetType="MenuItem">
                                    <Setter Property="Header" Value="{Binding Header}"/>
                                    <Setter Property="Command" Value="{Binding Command}"/>
                                    <Setter Property="CommandParameter" Value="{Binding CommandParameter}"/>
                                </Style>
                            </ContextMenu.ItemContainerStyle>
                        </ContextMenu>
                    </TextBlock.ContextMenu>
                </TextBlock>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

0 个答案:

没有答案