Collectionview Xamarin 外部 Viewmodel 内部的数据绑定不起作用,ui 未更新

data Binding inside Viewmodel outside Collectionview Xamarin is not working, ui is not updating

现在我正在尝试实现一个集合视图和一个 select 不同用户的离子。 为了获得 selected 用户的数量,我在 obersavle 集合之外定义了一个名为 _nrofselectedUser 的变量。它与我定义的 SelectedUser ObservableList 的 count() 相同。 ObservableCollection 工作正常,当我删除其中的一个对象时,我得到了所有的东西并更新了 ui。 但是我无法获得 nrofselectedUser 的数据绑定权限。

这是初始化 VielModel 的主页:

public partial class UserCollectionPage : ContentPage
{

    private UserCollectionViewModel _uvm;
    private UserDBHelper userDBHelper = new UserDBHelper();
    private int _nrOfSelectedUser { get; set; }
    public UserCollectionPage()
    {
        BindingContext = _uvm = new UserCollectionViewModel();
        InitializeComponent();

    }

这是 ModelView,称为 UserCollectionViewModel:

命名空间App1.ViewModels { public class UserCollectionViewModel : BaseViewModel { 私有 ObservableCollection _user;

    public ObservableCollection<object> _selectedUser { get; set; }

    private SelectionMode _selectionMode = SelectionMode.None;

    private int _nrOfSelectedUser { get; set; }

    public User SelectedItem { get; set; }

    public SelectionMode SelectionMode { get => _selectionMode; set => SetProperty(ref _selectionMode, value); }

    public ObservableCollection<User> User { get => _user; set => _user = value; }

    public ObservableCollection<object> SelectedUser { get => _selectedUser; set => _selectedUser = value; }

    public UserDBHelper userDBHelper = new UserDBHelper();

    public UserCollectionViewModel()
    {
        InitData();
        
        ShareCommand = new Command(OnShare);
        LongPressCommand = new Command<User>(OnLongPress);
        ClearCommand = new Command(OnClear);
        PressedCommand = new Command<User>(OnPressed);
        RefreshCommand = new Command(ExecuteRefreshCommand);
    }

    private void InitData()
    {
        _selectedUser = new ObservableCollection<object>();
        _user = userDBHelper.GetAllUserToCollection();
        _nrOfSelectedUser = SelectedUser.Count();
    }

    public int NrofSelectedUser
    {
        get => _nrOfSelectedUser;
        set
        {
            _nrOfSelectedUser = value;
            OnPropertyChanged(nameof(NrofSelectedUser));
        }
    }

    private void OnLongPress(User p)
    {
        try
        {
            // Use default vibration length
            Vibration.Vibrate();
            Console.WriteLine("LongPressed");
            if (_selectionMode == SelectionMode.None)
            {
                SelectionMode = SelectionMode.Multiple;
                SelectedUser.Add(p);
                _nrOfSelectedUser++;
                Console.Write("Add User");
            }
        }
        catch (FeatureNotSupportedException ex)
        {
            Console.WriteLine("Feature not supported on device" + ex);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }

    private async void OnPressed(User obj)
     {
        Console.WriteLine("User In Collection: " + SelectedUser.Count());
        if (_selectionMode != SelectionMode.None)
        {
            _nrOfSelectedUser++;
            Console.WriteLine("Test OnPress");
            if (_selectedUser.Count() == 0)
            {
                SelectionMode = SelectionMode.None;
            }
            else
            {
                Console.WriteLine("Test OnPress");
            }
            
        }
        else
        {
            await  App.Current.MainPage.DisplayToastAsync("Navigiere zu User Details");
        }
    }

这是 MainPageXAML

        <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
         x:Class="App1.View.UserCollectionPage"
         xmlns:pg="clr-namespace:App1.ViewModels"
         x:Name="UserCollectionView"
         xmlns:converters="clr-namespace:App1.Methods;assembly=App1">
<ContentPage.Resources>
    <ResourceDictionary>
        <converters:IntToString x:Key="IntToString" />
    </ResourceDictionary>
</ContentPage.Resources>
<NavigationPage.TitleView>
    <Grid >

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="0.5*"/>
            <ColumnDefinition Width="0.5*"/>

        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Label Grid.Column="0"
           MaxLines="1"
           Text="Patienten"
           FontSize="Medium"
           HorizontalOptions="StartAndExpand"
           VerticalOptions="Center"/>
        <StackLayout Grid.Column="1" 
                     HorizontalOptions="EndAndExpand"
                     Orientation="Horizontal">
        <Label Text="Selected:"
           VerticalOptions="Center"
           FontSize="Medium"
               HorizontalOptions="EndAndExpand"/>
            <Label Text="{Binding Path=BindingContext.NrofSelectedUser, Source={x:Reference UserCollectionView},Converter={StaticResource IntToString}}" VerticalOptions="Center" FontSize="Medium" HorizontalOptions="EndAndExpand"/>
            <Image
            Grid.Column="2" Source="https://img.icons8.com/external-tulpahn-flat-tulpahn/64/fa314a/external-bin-mobile-user-interface-tulpahn-flat-tulpahn.png"
                HorizontalOptions="EndAndExpand"/>
        </StackLayout>
    </Grid>
</NavigationPage.TitleView>

<StackLayout>
    <CollectionView x:Name="UserCV" SelectionMode="{Binding SelectionMode}" SelectedItems="{Binding SelectedUser}" ItemsSource="{Binding User}"

正如您在 NavigationPage.TitleView 中看到的那样,我想设置 nrofselectedUser,以便在 selectedUser 更改时更改。 但它不起作用,我尝试了不同的方法:

1.

2.

3.

所以在每次尝试时,nrofselectedUser 的初始化都在 InitData() 上进行。 所以数字一开始是0,这是正确的,也显示在应用程序中。

但在那之后,当我在集合视图中 select 用户时,UI 没有更新,无论我尝试了什么。

在 Debug 中,我可以看到,该值根据按下而变化,但我还设置了 nrofselectUser = SelectedUser.Count()

所以我不知道为什么数据绑定不起作用,

我认为它需要做一些事情,++ 或 nrofselectUser = SelectedUser.Count() 没有调用 baseView 中的 onpropertychanged 方法。但是我不知道怎么触发它...

请帮忙

顺便说一句,BaseViewModel

public abstract class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string name = null) => 
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

您正在递增 private 变量

_nrOfSelectedUser++;

相反,您需要增加 public 属性,这将导致 PropertyChanged 触发

NrofSelectedUser++;