首页 > 解决方案 > 显示链接时,集合视图中的项目未与 MVVM 一起显示

问题描述

我需要帮助来弄清楚为什么我的集合视图没有显示它绑定的数据。当我在调试模式下运行应用程序时,数据被填充到 Viewmodel 中并绑定。当我转到 View.xaml 并将鼠标悬停在其绑定的源上时,它会显示。

我已经提供了模型、模型视图、视图和视图背后的代码,甚至是在调试器中运行的视图的屏幕截图,显示绑定似乎正在工作。

我已经被困了一段时间,任何帮助将不胜感激。

我在调试模式下运行时看到的内容显示视图模型已绑定但未显示。

ContactsPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="Project_contact.Views.ItemsPage"
             Title="{Binding Title}"
             x:Name="BrowseItemsPage">

    <ContentPage.ToolbarItems>
        <ToolbarItem Text="Add" Clicked="AddItem_Clicked" />
    </ContentPage.ToolbarItems>


    <RefreshView IsRefreshing="{Binding IsBusy, Mode=TwoWay}" Command="{Binding LoadDataCommand}">
        
        <StackLayout>
            <Label x:Name="TopBanner" Text="Welcome Please wait..." />
            


            <StackLayout Orientation="Horizontal">
                <Label Text= "{Binding StringFormat='Welcome You have' }" />
            </StackLayout>
            <CollectionView x:Name="ItemsCollectionView2"
                ItemsSource="{Binding Contacts}">
               
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                      
                        <StackLayout Padding="10">
                            <Label Text="{Binding name}" 
                                
                                LineBreakMode="NoWrap" 
                                Style="{DynamicResource ListItemTextStyle}" 
                                FontSize="16" />
                            <Label Text="{Binding desc}" 
                                d:Text="Item descripton"
                                LineBreakMode="NoWrap"
                                Style="{DynamicResource ListItemDetailTextStyle}"
                                FontSize="13" />
                            
                            <StackLayout.GestureRecognizers>
                                <TapGestureRecognizer NumberOfTapsRequired="1" Tapped="OnContactSelected_Tapped"></TapGestureRecognizer>
                                <SwipeGestureRecognizer Direction="Left" />
                            </StackLayout.GestureRecognizers>
                            
                        </StackLayout>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </StackLayout>
        
    </RefreshView>
</ContentPage>

ContactsPage.xaml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

using Project_Contact.Models;
using Project_Contact.Views;
using Project_Contact.ViewModels;
using Project_Contact.Services;
using System.Data;

namespace Project_Contact.Views
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class ItemsPage : ContentPage
    {
        public ContactsViewModel viewModel { get; set; }
        public ContactStore contactStore { get; set; }

        public ContactsPage()
        {
            contactStore = new ContactStore(DependencyService.Get<Database>());
            viewModel = new ContactsViewModel(contactStore);
            viewModel.LoadDataCommand.Execute(null);
            BindingContext = viewModel;
            InitializeComponent();


        }

        async void OnItemSelected(object sender, EventArgs args)
        {
            var layout = (BindableObject)sender;
            var item = (Item)layout.BindingContext;
            await Navigation.PushAsync(new ItemDetailPage(new ItemDetailViewModel(item)));
        }

        async void AddItem_Clicked(object sender, EventArgs e)
        {
            await Navigation.PushModalAsync(new NavigationPage(new NewContactPage(contactStore)));
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
     
            viewModel.LoadDataCommand.Execute(true);
           
        }

        async void OnContactSelected_Tapped(object sender, EventArgs e)
        {
            var layout = (BindableObject)sender;
            var contact = (Contact)layout.BindingContext;
            await Navigation.PushAsync(new ContactDetailPage(new ContactDetailViewModel(contactStore,contact)));
        }

    }
}

ContactsPageViewModel.cs

using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading.Tasks;

using Xamarin.Forms;

using Project_contact.Models;
using Project_contact.Views;
using Project_contact.Services;

namespace Project_contact.ViewModels
{
    public class ContactsViewModel : BaseViewModel
    {
        public ObservableCollection<Contact> Contacts { get; set; } = new ObservableCollection<Contact>();
        public Command LoadContacts { get; private set; }
        public Command LoadDataCommand { get; private set; }
       // public Command load 
        public ContactStore contactStore;
        
        public int  numberofContacts { get; set; }
        public string TopBannerText { get; set; }



        public ContactsViewModel(ContactStore contactStore)
        {
            
            Title = "Browse";
            this.contactStore = contactStore;
            
            
            LoadDataCommand = new Command(async () => await ExecuteLoadDataCommand());
            
        }

        public  async Task ExecuteLoadDataCommand()
        {
            Contacts = new ObservableCollection<Contact>(await contactStore.GetContactsAsync());
            LoadContacts = new Command(async () => await ExecuteLoadContactsCommand());
           
            TopBannerText = String.Format("Welcome you have {0} contacts  ",numberofContacts);


        }

        async Task ExecuteLoadContactsCommand()
        {
            if (!IsBusy)
            {
                IsBusy = true;

                try
                {
                    if (Contacts.Count > 0)
                    {
                        Contacts.Clear();
                        numberofContacts = 0;
                    }
                    
                    var contacts = await contactStore.GetContactsAsync();
                    foreach (var contact in contacts)
                    {
                        Contacts.Add(contact);
                        numberofContacts++;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
                finally
                {
                    IsBusy = false;
                }
            }
           
        }

    }
}

联系人.cs

using System;
using System.Collections.Generic;
using System.Text;
using SQLite;

namespace Project_Contact.Models
{
    public class Contact
    {
        [PrimaryKey, AutoIncrement]
        public int id { get; set; }
        public string name { get; set; }
        public string  desc { get; set; }
        public string number {get; set;}

      
    }
}

标签: c#mvvmxamarin.formsxamarin.ios

解决方案


推荐阅读