Reputation: 9862
I added ListBox
to my XAML file which look like this:
<ListBox
SelectedIndex="{Binding SelectedIndex}"
ItemsSource="{Binding Answers}">
...
</ListBox>
My ViewModel class have these properties:
private int? selectedIndex;
public int? SelectedIndex
{
get => selectedIndex;
set
{
selectedIndex = value;
RaisePropertyChanged(nameof(SelectedIndex));
}
}
private ObservableCollection<string> answers;
public ObservableCollection<string> Answers
{
get => answers;
private set
{
answers = value;
RaisePropertyChanged(nameof(Answers));
}
}
Now when I click on the Item that is already selected I want to unselect this Item (so I think SelectedIndex = null
will do the job). How I can do it? I try to find a solution but without any success.
Is there any command which I could execute every time the ListBox
item is clicked? This command as a parameter must pass the index of clicked item. If there is a possibility like this it will be enough for me if You just show me how to create this command and pass the Item index as a parameter.
Upvotes: 0
Views: 740
Reputation: 128062
You can set up a PreviewMouseLeftButtonDown (or similar) event handler
<ListBox ...>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<EventSetter Event="PreviewMouseLeftButtonDown"
Handler="ListBoxItemPreviewMouseLeftButtonDown"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
that does just this:
private void ListBoxItemPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is ListBoxItem listBoxItem && listBoxItem.IsSelected)
{
listBoxItem.Dispatcher.InvokeAsync(() => listBoxItem.IsSelected = false);
}
}
Upvotes: 1