Reputation: 49
How to deselect the SelectedItem if the selected item does not meet the requirement using the collection view? Do I have to create a custom collection view? How to do on the override the OnPropertyChanged method? Thank you.
Upvotes: 0
Views: 2969
Reputation: 198
Working algorithm upon https://stackoverflow.com/a/64457513/1894630 solution:
private void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
CollectionView collectionV = sender as CollectionView;
Viewmodels.Slotviewmodel current;
if (e.CurrentSelection.Count == 0 || e.PreviousSelection.Count == 0)
{
if (e.CurrentSelection.Count != 0)
{
current = e.CurrentSelection[0] as Viewmodels.Slotviewmodel;
if (!current.available)
{
collectionV.SelectedItem = null;
}
}
return;
}
current = e.CurrentSelection[0] as Viewmodels.Slotviewmodel;
if (!current.available) //meet requirement
{
collectionV.SelectedItem = e.PreviousSelection[0];
}
}
Upvotes: 0
Reputation: 2064
If you are using MVVM design pattern, then you should be able to track the CollectionView
's SelectedItem
property in your ViewModel
, essentially using Binding in TwoWay
mode. Here is the sample:
YourView.xaml:
<CollectionView ItemsSource="Items" SelectedItem="SelectedItem"/>
YourViewModel.cs
public IList<string> Items{get;set;}
private string _selectedItem;
public string SelectedItem
{
get=>_selectedItem;
set
{
//if selected item is the same one, return
if(Equals(value,_selectedItem)) return;
//if the item doesn't meet the requirement, don't update the selected item in the view model
if(!ItemMeetsYourRequirement(value))
{
//raise property changed to notify view to change the selected item to previous one
OnPropertyChanged(nameof(SelectedItem));
return;
}
//if you are here, the selected item is changed and meets your requirements;
_selectedItem = value;
OnPropertyChanged(nameof(SelectedItem);
}
}
private bool ItemMeetsYourRequirement(string item) => return true; //add your logic here
Upvotes: 2
Reputation: 15816
You can deselecte
the SelectedItem
in the CollectionView_SelectionChanged
event:
private void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//var previous = e.PreviousSelection;
//var current = e.CurrentSelection;
CollectionView collectionV = sender as CollectionView;
if ()//meet requirement
{
}
else
{
//not meet requirement
collectionV.SelectedItem = null;
}
}
And in xaml:
<CollectionView SelectionChanged="CollectionView_SelectionChanged" SelectionMode="Single">
<CollectionView.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>Baboon</x:String>
<x:String>Capuchin Monkey</x:String>
<x:String>Blue Monkey</x:String>
</x:Array>
</CollectionView.ItemsSource>
</CollectionView>
Upvotes: 2