ListView 에서 선택한 셀에 대한 색상을 변경하는 방법입니다.

아래는 기본 적인 ListView 코드입니다.

        <ListView x:Name="originalListView"
                  RowHeight="30"
                  SeparatorVisibility ="Default"
                  SeparatorColor="Black"
                  Margin="10"                  >
            <ListView.Header>
                <StackLayout Orientation="Horizontal"
                             VerticalOptions="CenterAndExpand"
                             Padding="0"
                             Spacing="0"
                             BackgroundColor="Gray"
                             HeightRequest="30">
                    <Label  Text="항목"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            FontSize="12"
                            WidthRequest="80"/>
                    <Label  Text="데이터1"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            WidthRequest="80"
                            FontSize="12"/>
                    <Label  Text="데이터2"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            WidthRequest="80"
                            FontSize="12"/>
                </StackLayout>
            </ListView.Header>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                            <StackLayout>
                                <StackLayout VerticalOptions="CenterAndExpand"
                                             Orientation="Horizontal"
                                             Padding="0"
                                             Spacing="0">
                                    <Label  Text="{Binding Content}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                    <Label  Text="{Binding Data1}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                    <Label  Text="{Binding Data2}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                </StackLayout>
                            </StackLayout>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

위처럼 Page 에 위치 시킨 후 구동하면 아래와 같이 선택한 컬럼에 대해서 아래와 같이 나타납니다.

(선택 색상이 전혀 어울리지 않습니다.^^; - 안드로이드 버젼별로 색이 다름)

 

이상한 자주색이 맘에 들지 않습니다.; 선택한 컬럼에 대해 색상을 변경해봅시다.

먼저 .Net Standard 프로젝트에 ExtendedViewCell 클래스를 추가합니다.

using Xamarin.Forms;

namespace Test.Extended
{
    public class ExtendedViewCell : ViewCell
    {
        public static readonly BindableProperty SelectedBackgroundColorProperty =
            BindableProperty.Create("SelectedBackgroundColor",
                                    typeof(Color),
                                    typeof(ExtendedViewCell),
                                    Color.Default);

        public Color SelectedBackgroundColor
        {
            get { return (Color)GetValue(SelectedBackgroundColorProperty); }
            set { SetValue(SelectedBackgroundColorProperty, value); }
        }
    }
}

여기선 단순히 SelectedBackgroundColor 속성을 선언만 할 뿐입니다.

실질적인 동작은 각 장치별 렌더러에서 맡아서 처리하게됩니다.

 

Android 프로젝트로 가서 ExtendedViewCellRenderer 클래스를 추가합니다.

using Android.Content;
using Android.Graphics.Drawables;
using Android.Views;
using Test.Droid.ExtendedRenderer;
using Test.Extended;
using System.ComponentModel;
 
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(ExtendedViewCell), typeof(ExtendedViewCellRenderer))]
namespace Test.Droid.ExtendedRenderer
{
    public class ExtendedViewCellRenderer : ViewCellRenderer
    {
        private Android.Views.View cellCoreView;
        private Drawable unSelectedBackground;
        private bool isSelected;

        protected override Android.Views.View GetCellCore(
            Cell item, Android.Views.View convertView, ViewGroup parent, Context context)
        {
            this.cellCoreView = base.GetCellCore(item, convertView, parent, context);

            this.isSelected = false;
            this.unSelectedBackground = cellCoreView.Background;

            return cellCoreView;
        }

        protected override void OnCellPropertyChanged(object sender, PropertyChangedEventArgs args)
        {
            base.OnCellPropertyChanged(sender, args);

            if (args.PropertyName == "IsSelected")
            {
                this.isSelected = !this.isSelected;

                if (this.isSelected)
                {
                    var extendedViewCell = sender as ExtendedViewCell;
                    this.cellCoreView.SetBackgroundColor(extendedViewCell.SelectedBackgroundColor.ToAndroid());
                }
                else
                {
                    this.cellCoreView.SetBackground(this.unSelectedBackground);
                }
            }
        }
    }
}

 

iOS 프로젝트로 가서 ExtendedViewCellRenderer 클래스를 추가합니다.

using Test.Extended;
using Test.iOS.ExtendedRenderer;
using UIKit;

using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(ExtendedViewCell), typeof(ExtendedViewCellRenderer))]
namespace Test.iOS.ExtendedRenderer
{
    public class ExtendedViewCellRenderer : ViewCellRenderer
    {
        public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
        {
            var cell = base.GetCell(item, reusableCell, tv);
            var view = item as ExtendedViewCell;
            cell.SelectedBackgroundView = new UIView
            {
                BackgroundColor = view.SelectedBackgroundColor.ToUIColor(),
            };

            return cell;
        }
    }
}

사전 작업은 완료되었습니다.

 

이제 기본 코드에서 ExtendedViewCell 을 사용하도록 변경합니다. (굵게표시된부분)

        <ListView x:Name="extendedListView"
                  RowHeight="30"
                  SeparatorVisibility ="Default"
                  SeparatorColor="Black"
                  Margin="10"                  >
            <ListView.Header>
                <StackLayout Orientation="Horizontal"
                             VerticalOptions="CenterAndExpand"
                             Padding="0"
                             Spacing="0"
                             BackgroundColor="Gray"
                             HeightRequest="30">
                    <Label  Text="항목"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            FontSize="12"
                            WidthRequest="80"/>
                    <Label  Text="데이터1"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            WidthRequest="80"
                            FontSize="12"/>
                    <Label  Text="데이터2"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            WidthRequest="80"
                            FontSize="12"/>
                </StackLayout>
            </ListView.Header>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <extended:ExtendedViewCell SelectedBackgroundColor="LightGray">
                        <ViewCell.View>
                            <StackLayout>
                                <StackLayout VerticalOptions="CenterAndExpand"
                                             Orientation="Horizontal"
                                             Padding="0"
                                             Spacing="0">
                                    <Label  Text="{Binding Content}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                    <Label  Text="{Binding Data1}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                    <Label  Text="{Binding Data2}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                </StackLayout>
                            </StackLayout>
                        </ViewCell.View>
                    </extended:ExtendedViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

Selected Color 로 LightGray 를 설정한 결과는 아래과 같습니다.

완료!

ListView 는 데이터를 나열하여 표시해주는 컨트롤입니다.

더이상 설명은 필요 없을것 같으니 바로 시작하겠습니다.

신규 ContentPage 를 생성하여 ListViewPage.xaml 를 만듭니다.

ListViewPage.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="XamarinFormsStudy.ListViewPage">
    <ListView x:Name="MainListView" HasUnevenRows="True">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Orientation="Horizontal" Padding="10">
                        <Label Text="{Binding ID}"/>
                        <StackLayout VerticalOptions="Center">
                            <Label Text="{Binding Name}" Font="Large"/>
                            <Label Text="{Binding Age}" />
                            <Label Text="{Binding Dept}" Font="Bold" Opacity="0.6"/>
                            <Label Text="{Binding Desc}" Font="Small"/>
                        </StackLayout>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

위 내용을 설명하자면 ListView.ItemTemplate 은 리스트뷰에 바인딩될 항목에 대해서 일정한 모양으로 바인딩 될수 있도록 해주는

템플릿을 정의하기 위한 것이라고 보면됩니다.

<DataTemplate> <ViewCell > 의 내부에 데이터가 바인딩될 구조를 미리 정의 하면 데이터가 그 구조에 맞게 바인딩됩니다.

디자인 코드를 보면 ID는 왼쪽 끝으로 위치하고 다른 항목들 (Name,Age등) 은 오른쪽에 위치시켜 아래로 쭉 나열하여 위치시킨 것을 알수 있습니다.

이제 ListViewPage.xaml.cs 파일을 코딩합니다.

(설명은 주석으로..)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace XamarinFormsStudy
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ListViewPage : ContentPage
    {
        public ListViewPage()
        {
            InitializeComponent();

            //MainListView.ItemsSource = new List<string> { "AA", "BB", "CC" };

            // 데이터들을 정의합니다.
            ListViewTestData data1 = new ListViewTestData() { ID = 1, Name = "user1", Age = 34, Dept = "Povice", Desc = "TestUser1" };
            ListViewTestData data2 = new ListViewTestData() { ID = 2, Name = "user2", Age = 31, Dept = "Povice", Desc = "TestUser2" };
            ListViewTestData data3 = new ListViewTestData() { ID = 3, Name = "user3", Age = 30, Dept = "Povice", Desc = "TestUser3" };
            ListViewTestData data4 = new ListViewTestData() { ID = 4, Name = "user4", Age = 40, Dept = "kjun", Desc = "TestUser4" };

            List<ListViewTestData> testData = new List<ListViewTestData>();
            testData.Add(data1);
            testData.Add(data2);
            testData.Add(data3);
            testData.Add(data4);

            // ListView 의 Source 에 적용하면 디자인 코드의 itemtemplate 에 바인딩될 항목을들 찾아 바인딩됩니다.
            MainListView.ItemsSource = testData;
        }
    }

    /// <summary>
    ///  ListView 에 바인딩될 데이터입니다.
    /// </summary>
    public class ListViewTestData
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Dept { get; set; }
        public string Desc { get; set; }
    }
}

 

결과는 아래와 같습니다.

 

LisView 는 디자인을 어떻게 하냐에 따라서 정말 달라보입니다.

Styling 하는 방법도 시간이 된다면 포스팅 할 예정입니다.

 

참고

http://blog.naver.com/goldrushing/220668652665

https://developer.xamarin.com/guides/xamarin-forms/user-interface/listview/

https://www.youtube.com/watch?v=N0e3fPisIw8&list=PLpbcUe4chE7-5t2mlamz6yB0qzAfO5Yln&index=9

GitHub > https://github.com/knagjun/XamarinForms

'Xamarin' 카테고리의 다른 글

(Xamarin Forms) 7.SQLite - PlugIn.SQLite  (0) 2017.07.12
(Xamarin Forms) Bluetooth - 링크  (0) 2017.07.11
(Xamarin Forms) 6.ListView  (0) 2017.07.11
(Xamarin Forms) 5.Chart - OxyPlot (Line Chart)  (0) 2017.07.11
(Xamarin Forms) 5.Chart - OxyPlot  (0) 2017.07.10
(Xamarin Forms) 4.Image  (0) 2017.07.06

+ Recent posts