根據教學影片 -
用 Listview 展現集合資料 的練習,重點在於
- ItemSource:ListView 的資料來源
- ToString():ListView Item 內容顯示
- SelectedItem:指定預設值
- SeparatorVisibility 和 SeparatorColor:分隔線和分隔線顏色
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:local="clr-namespace:ListViewBase"
x:Class="ListViewBase.Base">
<ContentPage.BindingContext>
<local:ViewModel/>
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout>
<ListView
ItemsSource="{Binding ItemsSource}"
SelectedItem="{Binding SelectedItem ,Mode=TwoWay}"
SeparatorVisibility="Default"
SeparatorColor="Green"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
ViewModel
using System.Linq;
using System.ComponentModel;
namespace ListViewBase
{
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string PropertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
public IList<Product> ItemsSource { get; set; }
public ViewModel()
{
ItemsSource = Product.GetData();
// 預設值為第三筆
// SelectedItem = ItemsSource.Skip(2).FirstOrDefault();
// 指定預設值為 "煙火"
SelectedItem = ItemsSource.Where(w => w.Name == "煙火").FirstOrDefault();
}
public Product SelectedItem { get; set; }
}
}
Model
namespace ListViewBase
{
public class Product
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
public static List<Product> GetData()
{
return new List<Product>
{
new Product() { Name = "楓葉" } ,
new Product() { Name = "樹" } ,
new Product() { Name = "花" } ,
new Product() { Name = "煙火" } ,
new Product() { Name = "夜景" }
};
}
}
}
執行結果
沒有留言:
張貼留言