首页 > 解决方案 > 无法使用命令 NO EVENT 在 CollectionView 中选择相同的项目两次

问题描述

我无法选择一个项目两次。我不使用事件。我用命令和 ViewModel 管理一切。我只能找到代码背后的解决方案。

CodeBehind 解决方案 ((CollectionView)sender).SelectedItem = null;

我不使用发件人,所以这个变体不起作用。

这是我的命令调用:

<CollectionView SelectionMode="Single"
                ItemsSource="{Binding Source={RelativeSource AncestorType={x:Type Lib:Profile_Model}}, 
                                       Path=UserPartyById}"
                ItemTemplate="{StaticResource Profile_Party_DataTemplate}"
                SelectedItem="{Binding Source={RelativeSource AncestorType={x:Type Lib:Profile_Model}}, 
                                      Path=SelectedItem}"

                SelectionChangedCommand="{Binding Source={RelativeSource AncestorType={x:Type Lib:Profile_Model}}, 
                                      Path=GoPartyDetailCommand}">

    <CollectionView.ItemsLayout>
        <LinearItemsLayout ItemSpacing="5" Orientation="Horizontal" />
    </CollectionView.ItemsLayout>

</CollectionView>
GoPartyDetailCommand = new Command(GoPartyDetail);

private Merged_Model selectedItem;
public Merged_Model SelectedItem
{
    get => selectedItem;
    set => SetPorperty(ref selectedItem, value);
}

public async void GoPartyDetail()
{
    Preferences.Set("SelectPartyId", SelectedItem.Id);
    Preferences.Set("FK_User", SelectedItem.FK_User);
    await _navigationService.NavigateToAsync<PartyDetail_ViewModel>();
}

H

标签: xamarincommandcollectionview

解决方案


您可以使用将您的视图模型SelectionChangedCommandParameter传递ColletionView给您的视图模型,然后您可以使用清理SelectedItem.

<CollectionView
     x:Name = "collectionview"
     SelectionMode="Single"
     ItemsSource="{Binding Source={RelativeSource AncestorType={x:Type Lib:Profile_Model}}, 
                               Path=UserPartyById}"
     ItemTemplate="{StaticResource Profile_Party_DataTemplate}"
     SelectedItem="{Binding Source={RelativeSource AncestorType={x:Type Lib:Profile_Model}}, 
                              Path=SelectedItem}"

     SelectionChangedCommand="{Binding Source={RelativeSource AncestorType={x:Type Lib:Profile_Model}},Path=GoPartyDetailCommand}"   
     SelectionChangedCommandParameter="{x:Reference collectionview}"
        >

        <CollectionView.ItemsLayout>
            <LinearItemsLayout ItemSpacing="5" Orientation="Horizontal" />
        </CollectionView.ItemsLayout>

</CollectionView>

然后在您的视图模型中:

public ICommand GoPartyDetailCommand => new Command<CollectionView>(GoPartyDetail);

public async void GoPartyDetail(CollectionView collectionview)
{
   // you could get the collectionview,then clean the selectItem
    Preferences.Set("SelectPartyId", SelectedItem.Id);
    Preferences.Set("FK_User", SelectedItem.FK_User);
    await _navigationService.NavigateToAsync<PartyDetail_ViewModel>();

}

推荐阅读