2

I've got

<ListView SelectionMode="Single" SelectedIndex="0" ItemsSource="{Binding AccountViewModels}" SelectedItem="{Binding SelectedItem}" Style="{StaticResource AccountsList}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <LocalViews:AccountView Margin="{StaticResource ControlMargin}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ListView>

Is there a way to disable deselection of an item from the ListView (i.e. ctrl+click)? In other words, I don't want the user to be able to de-select an item, but of course it's OK to select another item.

hyankov
  • 4,049
  • 1
  • 29
  • 46
  • Possible duplicate of [Prevent user from deselecting an item in a ListBox?](http://stackoverflow.com/questions/5845512/prevent-user-from-deselecting-an-item-in-a-listbox) – Drew Noakes Jan 08 '17 at 15:12
  • Possible duplicate of [Do not allow unselect/deselect in ListBox](http://stackoverflow.com/questions/5815844/do-not-allow-unselect-deselect-in-listbox) – Drew Noakes Jan 08 '17 at 15:13

2 Answers2

7

Since this functionality is purely view/control related it should not be implemented in the view model but you could handle the PreviewMouseLeftButtonDown event of the ListBoxItem container like this:

<ListView SelectionMode="Single" SelectedIndex="0" ItemsSource="{Binding AccountViewModels}" SelectedItem="{Binding SelectedItem}" Style="{StaticResource AccountsList}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ItemPreviewMouseLeftButtonDown" />
        </Style>
    </ListBox.ItemContainerStyle>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <LocalViews:AccountView Margin="{StaticResource ControlMargin}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ListView>

private void ItemPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    ListBoxItem lbi = sender as ListBoxItem;
    e.Handled = lbi.IsSelected;
}
mm8
  • 163,881
  • 10
  • 57
  • 88
0

One way to handle this would be to use binding and add logic to disallow de-selection in the view model.

From this answer, change the IsSelected as follows:

private bool isSelected;

public bool IsSelected
{
    get { return isSelected; }
    set
    {
        if (value && !isSelected)
        {
            isSelected = value;
            RaisePropertyChanged("IsSelected");
        }
    }
}
Community
  • 1
  • 1
RQDQ
  • 15,461
  • 2
  • 32
  • 59