Search code examples
c#wpftreeviewwinrt-xamltreeviewitem

TreeViewItem do not get highlighted on Single click WPF


I have a simple tree, it works fine, but it does not get highlighted on Single click, the user needs to double click.

The commands bonded to it works fine on single click.

<TreeView ItemsSource="{Binding ElementsTypes}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate>
                <TextBlock Text="{Binding Name}">
                    <TextBlock.InputBindings>
                        <MouseBinding Gesture="LeftClick"
                                      Command="{Binding ElementsCommand}"
                                      CommandParameter="{Binding}" />
                    </TextBlock.InputBindings>
                </TextBlock>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
</TreeView>

Solution

  • That's because your MouseBinding is "stealing" your left click. One possible solution would be to add IsSelected property to your ViewModel and set it to true on ElementsCommand:

    <TreeView.ItemContainerStyle>
          <Style TargetType="{x:Type TreeViewItem}">
               <Setter Property="IsSelected" Value="{Binding IsSelected}" />
          </Style>
    </TreeView.ItemContainerStyle>
    
    
    public class MyTreeElement
    {
        private bool _IsSelected;
        public bool IsSelected
        {
            get { return _IsSelected; }
            set 
              { 
                  _IsSelected = value; 
                  OnPropertyChanged("IsSelected");
              }
        }
        private void ElementsCommandMethod(object item)
        {
            Console.WriteLine("ElementsCommand");
            IsSelected = true;
        }
    }
    

    This way you will also know which item in your ViewModel is selected and will be able to manipulate the selection programmatically from the ViewModel.