XAML in Xamarin.Forms 基礎篇 電子書

XAML in Xamarin.Forms 基礎篇 電子書
XAML in Xamarin.Forms 基礎篇 電子書

Xamarin.Forms 快速入門 電子書

Xamarin.Forms 快速入門 電子書
Xamarin.Forms 快速入門 電子書

2017/02/19

Xamarin FAQ 2-18 : 在ListView中,如何根據紀錄類型,顯示出不同的樣貌(簡單方法)

問題

繼續 Xamarin FAQ 2-17的問題,這個時候,若每筆紀錄要出現的內容或者格式,想要依據當時的資料內容,進行變更要顯示的資料格式或者內容,這個時候,可以使用哪種技術呢?

解答

這個問題,一樣可以有多種技術可以選擇,在這裡,我們使用了在 ViewModel 中來處理;主要的設計方法為,我們需要在 ViewModel 內加入一些其他屬性,這些屬性的內容會依據當時的資料內容,進行動態的調整其物件值。在底下的 XAML 中,我們希望每筆紀錄中,當紀錄資料的出生入其大於等於1980,則文字顏色要設定成為 綠色,否則,文字顏色要設定成為 紅色。因此,每個文字的顏色,並不是固定顏色值,而是綁定 ViewModel 內的某個屬性。
        <ListView 
            ItemsSource="{Binding People}"
            >
            <ListView.ItemTemplate>
                <DataTemplate >
                    <ViewCell>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="0.4*" />
                                <ColumnDefinition Width="0.3*" />
                                <ColumnDefinition Width="0.3*" />
                            </Grid.ColumnDefinitions>
                            <Label Text="{Binding Name}" TextColor="{Binding ShowColor}" FontAttributes="Bold" />
                            <Label Grid.Column="1" Text="{Binding DateOfBirth, StringFormat='{0:d}'}" TextColor="{Binding ShowColor}" />
                            <Label Grid.Column="2" Text="{Binding Location}" TextColor="{Binding ShowColor}" HorizontalTextAlignment="End" />
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
在 ViewModel 中,當這個頁面要顯示之前,ViewModel 的 OnNavigatedTo 方法會被執行,此時,我們將會進行要顯示在 ListView 內所有物件的值,就在此時,我們判斷每筆紀錄的生日欄位,若出生年份大於 1980,則會設定 ShowColor 這個屬性值為綠色,否則,設定為紅色。經過這樣處理,ListView 內的每筆紀錄文字,就會顯示不同的顏色了。
        public void OnNavigatedTo(NavigationParameters parameters)
        {
            People = new ObservableCollection<Person> {
                new Person ("Kath", new DateTime (1985, 11, 20), "France"),
                new Person ("Steve", new DateTime (1975, 1, 15), "USA"),
                new Person ("Lucas", new DateTime (1988, 2, 5), "Germany"),
                new Person ("John", new DateTime (1976, 2, 20), "USA"),
                new Person ("Tariq", new DateTime (1987, 1, 10), "UK"),
                new Person ("Jane", new DateTime (1982, 8, 30), "USA"),
                new Person ("Tom", new DateTime (1977, 3, 10), "UK")
            };

            foreach (var item in People)
            {
                if(item.DateOfBirth.Year >= 1980)
                {
                    item.ShowColor = Color.Green;
                }
                else
                {
                    item.ShowColor = Color.Red;
                }
            }
        }
Xamarin-跨平台手機應用程式設計入門-粉絲團

沒有留言:

張貼留言