xamarin 关于集合视图取消选择SelectedItem

w6mmgewl  于 2022-12-07  发布在  其他
关注(0)|答案(3)|浏览(178)

如果所选项目不满足使用集合视图的要求,如何取消选择SelectedItem?我必须创建自定义集合视图吗?如何覆盖OnPropertyChanged方法?谢谢。

frebpwbc

frebpwbc1#

您可以在CollectionView_SelectionChanged事件中deselecteSelectedItem

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;

    }
}

在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>
wpx232ag

wpx232ag2#

如果您使用MVVM设计模式,那么您应该能够在ViewModel中跟踪CollectionViewSelectedItem属性,实际上是在TwoWay模式下使用Binding。
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
nlejzf6q

nlejzf6q3#

https://stackoverflow.com/a/64457513/1894630解决方案的工作算法:

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

相关问题