2016-04-11 3 views
2

Я пытаюсь создать простую страницу с ListView и Button «Добавить», которая просто добавляет еще один элемент в список со счетом и меткой времени.Xamarin.Forms заполнить список

App.cs

namespace App1 
{ 
    public class App : Application 
    { 
     public App() 
     { 
      // The root page of your application 
      MainPage = new NavigationPage(new Page1()); 
     } 
    } 
} 

Как вы можете видеть, я создал Page.xaml и Page.xaml.cs.

Page.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="App1.Page1"> 
    <StackLayout Orientation="Vertical" VerticalOptions="FillAndExpand"> 
    <Label Text="Inizio" VerticalOptions="Start"/> 
    <ListView VerticalOptions="FillAndExpand" x:Name ="list"> 
    </ListView> 
    <Label Text="Fine" VerticalOptions="End"/> 
    </StackLayout> 
    <ContentPage.ToolbarItems> 
    <ToolbarItem x:Name="add"> 
     <ToolbarItem.Icon> 
     <OnPlatform 
      x:TypeArguments="FileImageSource" 
      iOS="appbar.add.png" 
      Android="appbar.add.png" 
      WinPhone="appbar.add.png" 
     /> 
     </ToolbarItem.Icon> 
    </ToolbarItem> 
    </ContentPage.ToolbarItems> 
</ContentPage> 

Page.xaml.cs

namespace App1 
{ 
    public partial class Page1 : ContentPage 
    { 
     int count = 0; 
     ObservableCollection<TextCell> cells = new ObservableCollection<TextCell>(); 

     public Page1() 
     { 
      InitializeComponent(); 
      //this.ToolbarItems.Add(new ToolbarItem { Text = "Add" }); 
      add.Clicked += Add_Clicked; 
     } 

     private void Add_Clicked(object sender, EventArgs e) 
     { 
      cells.Add(new TextCell { Text = count.ToString(), Detail = DateTime.Now.ToString("dd/MM/yyyy --> hh:mm:ss") }); 
      list.ItemsSource = cells; 
      count++; 
     } 
    } 
} 

Теперь все работает, но проблема заключается в List. У меня есть List, заполненный TextCells, и каждый из них имеет свойство, которое я установил. Однако, List заполняется элементами только текстом «Xamarin.Forms.TextCell».

Это моя первая попытка с Xamarin, что я делаю неправильно?

ответ

1

Хотя выше ответ заполняет концептуальный пробел в вашей реализации (+1 за это), но это Безразлично дайте вам общее решение проблемы, которую вы хотите решить. Пожалуйста, найдите решение ниже.

Это ваш CodeBehindFile класса Page.

namespace stackQues 
{ 
    public partial class Page : ContentPage 
    { 
     int count = 0; 
     List<TextCellItem> data = new MenuData(); 
     public Page() 
     { 
      InitializeComponent(); 
      //this.ToolbarItems.Add(new ToolbarItem { Text = "Add" }); 

     } 

     private void Add_Clicked(object sender, EventArgs e) 
     { 
      //cells.Add(new TextCell { Text = count.ToString(), Detail = DateTime.Now.ToString("dd/MM/yyyy --> hh:mm:ss") }); 


      data.Add (new TextCellItem { 
       TextLabel = count.ToString(), 
       DetailTextLabel = DateTime.Now.ToString ("dd/MM/yyyy --> hh:mm:ss") 
      }); 
      count++; 
      list.ItemsSource = data; 
      list.ItemTemplate = new DataTemplate(typeof(YourTextCell)); 

     } 
    } 
} 

Здесь MenuData является

namespace stackQues 
{ 
    class MenuData: List<TextCellItem> 
    { 
     public MenuData() 
     { 
     } 
    } 
} 

TextCellItem выглядит следующим образом

namespace stackQues 
{ 
    public class TextCellItem 
    { 
     public string TextLabel { get; set;} 
     public string DetailTextLabel { get; set;} 
    } 
} 

YourTextCell выглядит следующим образом

namespace stackQues 
{ 
    class YourTextCell:TextCell 
    { 
     public YourTextCell() { 
      this.SetBinding (TextCell.TextProperty, "TextLabel"); 
      this.SetBinding (TextCell.DetailProperty, "DetailTextLabel"); 
     } 
    } 
} 

Моих Xa разметка немного отличается, но предназначенная для каких-то целей

<?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="stackQues.Page"> 
<StackLayout Orientation="Vertical" VerticalOptions="FillAndExpand"> 
    <Label Text="Inizio" VerticalOptions="Start"/> 
    <ListView VerticalOptions="FillAndExpand" x:Name ="list"> 
    </ListView> 
    <Label Text="Fine" VerticalOptions="End"/> 
    <Button Text = "add" Clicked = "Add_Clicked" ></Button> 
    </StackLayout> 
<!-- <ContentPage.ToolbarItems> 
    <ToolbarItem x:Name="add"> 
     <ToolbarItem.Icon> 
     <OnPlatform 
      x:TypeArguments="FileImageSource" 
      iOS="appbar.add.png" 
      Android="cross.png" 
      WinPhone="appbar.add.png" 
     /> 
     </ToolbarItem.Icon> 
    </ToolbarItem> 
    </ContentPage.ToolbarItems>--> 
</ContentPage> 
+0

я собираюсь отметить это как правильные, так как он работает, и это очень хорошо объяснен. Только один вопрос: почему пользовательский List , а не просто List ? только для того, чтобы быть готовым к будущим реализациям? –

+1

Ah отлично, что будет делать, на самом деле у меня был этот шаблон из моего решения, где я добавляю некоторые элементы в класс menuData, поэтому не удосужился его удалить. –

2

Вы должны определить шаблон элемента

Это пример Xamarin документации

class Person 
{ 
    public string FullName 
    { 
    get; 
    set; 
    } 

    public string Address 
    { 
    get; 
    set; 
    } 
} 

void SetupView() 
{ 
    var template = new DataTemplate (typeof (TextCell)); 

    // We can set data bindings to our supplied objects. 
    template.SetBinding (TextCell.TextProperty, "FullName"); 
    template.SetBinding (TextCell.DetailProperty, "Address"); 

    // We can also set values that will apply to each item. 
    template.SetValue (TextCell.TextColorProperty, Color.Red); 

    itemsView.ItemTemplate = template; 
    itemsView.ItemsSource = new[] { 
    new Person { FullName = "James Smith", Address = "404 Nowhere Street" }, 
    new Person { FullName = "John Doe", Address = "404 Nowhere Ave" } 
    }; 
} 
Смежные вопросы