How to remove selection in ListView by clicking on blank space or any other control in UI?

Sarah 186 Reputation points
2022-03-12T14:22:24.6+00:00

I am using a ListView and I want to disable the selected item when I click anywhere in the UI or click another control in the UI.

 <ListView x:Name="View" Grid.Row="1" Grid.Column="0" ItemsSource="{Binding View}"  ScrollViewer.HorizontalScrollBarVisibility="Disabled" IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding Contact}" SelectionMode="Single">
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,686 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 19,306 Reputation points
    2022-03-12T19:23:40.607+00:00

    Hi SYarah,
    you can use an attached property in ContactListingViewModel:

        <ListView Grid.Row="1" Grid.Column="0"   
                  ItemsSource="{Binding View}"    
                  ScrollViewer.HorizontalScrollBarVisibility="Disabled"   
                  IsSynchronizedWithCurrentItem="True"   
                  SelectedItem="{Binding Contact}"  
                  local:ContactListingViewModel.AttPropListView="True">  
      
    ...  
      
        #region attached property  
        public static readonly DependencyProperty AttPropListViewProperty =  
            DependencyProperty.RegisterAttached("AttPropListView", typeof(bool), typeof(ContactListingViewModel), new PropertyMetadata(false, OnPropChanged));  
        public static bool GetAttPropListView(DependencyObject obj) => (bool)obj.GetValue(AttPropListViewProperty);  
        public static void SetAttPropListView(DependencyObject obj, bool par) => obj.SetValue(AttPropListViewProperty, par);  
        private static void OnPropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)  
        {  
          ListView lv = d as ListView;  
          if (lv == null) return;  
          lv.PreviewMouseLeftButtonDown += (s, mbe) =>  
          {  
            ContactListingViewModel vm = (ContactListingViewModel)(lv.DataContext);  
            vm.Contact = null;  
            vm.OnPropertyChanged(nameof(Contact));  
          };  
        }  
        #endregion  
    

    Result:

    182429-x.gif