hyankov
hyankov

Reputation: 4130

How to disable deselection of items in ListView?

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.

Upvotes: 2

Views: 1611

Answers (2)

mm8
mm8

Reputation: 169210

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;
}

Upvotes: 7

RQDQ
RQDQ

Reputation: 15569

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");
        }
    }
}

Upvotes: 0

Related Questions