2016-07-28 7 views
0

Я создаю Xamarin.Forms Portable Application. У меня есть база данных в моей Visual Studio, и я хочу отображать данные внутри нее в Xamarin ListView. Но всякий раз, когда я это делаю, данные не отображаются на моем Xamarin.Droid, оставляя только пустое место. Я попробовал это в UWP, и это сработало. Как я это сделаю в своем Xamarin.Droid?Xamarin.Forms: ListView не отображается на Xamarin.Droid

(Скриншот моего Xamarin.Droid)

enter image description here

Обратите внимание, что ListView по-прежнему занимают пространство, даже если не отображаются все записи. Как вы думаете, в чем причина этого? Я даже проверяю это в своем WEB API, если данные извлекаются, и это означает.

Смысл, реальная проблема возникает только при отображении записей в ListView. Надеюсь, ты поможешь мне.

Вот коды, которые я пробовал.

ClientList.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" 
     x:Class="XamarinFormsDemo.Views.ClientListPage" 
     xmlns:ViewModels="clr-namespace:XamarinFormsDemo.ViewModels;assembly=XamarinFormsDemo" 
     xmlns:controls="clr-namespace:ImageCircle.Forms.Plugin.Abstractions;assembly=ImageCircle.Forms.Plugin.Abstractions" 
     BackgroundImage="bg3.jpg" 
     Title="Client List"> 


    <ContentPage.BindingContext> 
    <ViewModels:CustomerVM/> 
    </ContentPage.BindingContext> 
    <StackLayout Orientation="Vertical"> 

    <SearchBar Placeholder="Search" Text="{Binding Keyword}" SearchCommand="{Binding SearchCommand}" x:Name="txtSearch" /> 

    <ListView ItemsSource="{Binding CustomerList}" 
      HasUnevenRows="True"> 
     <ListView.ItemTemplate> 
    <DataTemplate> 
     <ViewCell> 
     <Grid Padding="10" RowSpacing="10" ColumnSpacing="5"> 
      <Grid.RowDefinitions> 
      <RowDefinition Height="Auto"/> 
      <RowDefinition Height="*"/> 
      </Grid.RowDefinitions> 
      <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="Auto"/> 
      <ColumnDefinition Width="*"/> 
      </Grid.ColumnDefinitions> 

      <controls:CircleImage Source="icon.png" 
       HeightRequest="66" 
       HorizontalOptions="CenterAndExpand" 
       Aspect="AspectFill" 
       WidthRequest="66" 
       Grid.RowSpan="2" 
       /> 


      <Label Grid.Column="1" 
       Text="{Binding CUSTOMER_NAME}" 
       TextColor="#24e97d" 
       FontSize="24"/> 



      <Label Grid.Column="1" 
        Grid.Row="1" 
        Text="{Binding CUSTOMER_CODE}" 
        TextColor="White" 
        FontSize="18" 
        Opacity="0.6"/> 


      <Label Grid.Column="1" 
       Grid.Row="2" 
       Text="{Binding CUSTOMER_CONTACT}" 
       TextColor="White" 
       FontSize="18" 
       Opacity="0.6"/> 



     </Grid> 
     </ViewCell> 
    </DataTemplate> 
    </ListView.ItemTemplate> 

</ListView> 


    <StackLayout Orientation="Vertical" 
     Padding="30,10,30,10" 
     HeightRequest="20" 
     BackgroundColor="#24e97d" 
     VerticalOptions="Center" 
     Opacity="0.5"> 
    <Label Text="© Copyright 2016 SMESOFT.COM.PH All Rights Reserved " 
     HorizontalTextAlignment="Center" 
     VerticalOptions="Center" 
     HorizontalOptions="Center" /> 
    </StackLayout> 
    </StackLayout> 

</ContentPage> 

ClientListViewModel.cs

using System; 
using System.Collections.Generic; 
using System.Collections.ObjectModel; 
using System.ComponentModel; 
using System.Diagnostics; 
using System.Linq; 
using System.Runtime.CompilerServices; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Input; 
using Xamarin.Forms; 
using XamarinFormsDemo.Models; 
using XamarinFormsDemo.Services; 

namespace XamarinFormsDemo.ViewModels 
{ 
    public class CustomerVM : INotifyPropertyChanged 
    { 


    private List<Customer> _customerList; // keep all customers 
    private List<Customer> _searchedCustomerList; // keep a copy for searching 
    private Customer _selectedCustomer = new Customer(); 

    private string _keyword = ""; 
    public string Keyword 
    { 
     get 
     { 
      return _keyword; 
     } 
     set 
     { 
      this._keyword = value; 

      // while keyword changed we filter Employees 
      //Filter(); 
     } 
    } 



    private void Filter() 
    { 
     if (string.IsNullOrWhiteSpace(_keyword)) 
     { 
      CustomerList = _searchedCustomerList; 

     } 
     else 
     { 
      // var lowerKeyword = _keyword.ToLower(); 
      CustomerList = _searchedCustomerList.Where(r => r.CUSTOMER_NAME.ToLower().Contains(_keyword.ToLower())).ToList(); 
      // EmployeesList = _searchedEmployeesList.Where(r => r.EMPLOYEE_NAME.Contains(_keyword)).ToList(); 


     } 
    } 




    public List<Customer> CustomerList 
    { 
     get 
     { 
      return _customerList; 
     } 
     set 
     { 
      _customerList = value; 
      OnPropertyChanged(); 
     } 
    } 


    public ICommand SearchCommand 
    { 
     get 
     { 
      return new Command((sender) => 
      { 
       //var searchBar = (SearchBar)sender; 
       //this.Keyword = searchBar.Text; 
       Filter(); 
      }); 
     } 
    } 



    public CustomerVM() 
    { 
     InitializeDataAsync(); 
    } 

    private async Task InitializeDataAsync() 
    { 
     var customerServices = new CustomerServices(); 
     _searchedCustomerList = await customerServices.GetCustomerAsync(); 
     CustomerList = await customerServices.GetCustomerAsync(); 

    } 


    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) 
    { 
     var handler = PropertyChanged; 
     if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
    } 


    } 
} 

CustomerService.cs

using Plugin.RestClient; 
using System; 
using System.Collections.Generic; 
using System.Collections.ObjectModel; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using XamarinFormsDemo.Models; 

namespace XamarinFormsDemo.Services 
{ 
    public class CustomerServices 
    { 
    public async Task<List<Customer>> GetCustomerAsync() 
    { 
     RestClient_Customer<Customer> restClient = new RestClient_Customer<Customer>(); 

     var customerList = await restClient.GetCustomerAsync();//yung getasync ay pantawag as restclient 

     return customerList; 
     } 


    } 
} 

RestClient.cs

public class RestClient_Customer <T> 
{ 


    private const string WebServiceUrl = "http://localhost:50857/api/Customer/"; 

    public async Task<List<T>> GetCustomerAsync() 
    { 
     var httpClient = new HttpClient(); 

     var json = await httpClient.GetStringAsync(WebServiceUrl); 

     var taskModels = JsonConvert.DeserializeObject<List<T>>(json); 

     return taskModels; 
    } 
} 
+1

Try, как испытание, убирая 'StackLayout', который вокруг' ListView' –

+0

@GeraldVersluis я попробовал это сразу сэр. Но пока не отображается ListView. –

ответ

0

В вашей ViewModel Изменить

public List<Customer> CustomerList 

к

public ObservableCollection<Customer> CustomerList 

и в вашем XAML, изменить этот

<ListView ItemsSource="{Binding CustomerList}" 

этому

<ListView ItemsSource="{Binding CustomerList, Mode=TwoWay}" 
+0

Это не сработало. Ничего не изменилось. –

+0

Можете ли вы разместить проект на github, чтобы я мог работать с моей машины? – BraveHeart

+0

Я не знаю, как использовать GitHub Sir. Могу ли я просто отправить его вам по электронной почте? –

Смежные вопросы