728x90
반응형

SfListViewTestView.xaml 에서 SfListView.GroupHeaderTemplate 를 정의하여 표시될 양식을 정의합니다.
아래 내용은 헤더에 키에 해당하는 내용과 개수를 보여주도록 합니다.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="MauiApp1.SfListViewTestView"
             xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:syncfusion="clr-namespace:Syncfusion.Maui.ListView;assembly=Syncfusion.Maui.ListView"
             xmlns:sys="clr-namespace:System;assembly=netstandard"
             xmlns:local="clr-namespace:MauiApp1.Defines"
             xmlns:data="clr-namespace:Syncfusion.Maui.DataSource;assembly=Syncfusion.Maui.DataSource"
             Title="SfListView"
             BackgroundColor="White">
    <ContentPage.Resources>
        <x:Double x:Key="fontSize">24</x:Double>
        <OnPlatform x:Key="textColor" x:TypeArguments="Color">
            <On Platform="iOS" Value="Red" />
            <On Platform="Android" Value="LightGray" />
            <On Platform="UWP" Value="#80FF80" />
        </OnPlatform>
    </ContentPage.Resources>
    <Grid Padding="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <!--<RowDefinition Height="Auto"/>-->
        </Grid.RowDefinitions>
        <!--<Label 
            Text="{x:Static local:Constants.SfListViewTitle}"
            FontSize="{StaticResource fontSize}" 
            TextColor="{StaticResource textColor}" 
            HorizontalOptions="Center" 
            Margin="5">
            <Label.Text>
                <x:Static Member="local:Constants.SfListViewTitle"/>
            </Label.Text>
        </Label>-->
        <SearchBar 
            x:Name="filterText"
            HeightRequest="40"
            Grid.Row="0" 
            Placeholder="Search.."
            TextChanged="OnFilterTextChanged"
            TextColor="Black"/>
        <syncfusion:SfListView
            Margin="5"
            Grid.Row="1" 
            x:Name="listView"
            ItemSize="100" 
            ItemsSource="{Binding BookInfo}"
            SelectionBackground="Skyblue">
            <syncfusion:SfListView.ItemsLayout>
                <syncfusion:LinearLayout />
            </syncfusion:SfListView.ItemsLayout>
            <syncfusion:SfListView.SelectedItemTemplate>
                <DataTemplate>
                    <Grid x:Name="grid" BackgroundColor="RoyalBlue">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="0.4*" />
                            <RowDefinition Height="0.6*" />
                        </Grid.RowDefinitions>
                        <Label Text="{Binding BookName}"  FontAttributes="Bold" TextColor="Black" FontSize="25"  />
                        <Label Grid.Row="1" Text="{Binding BookDescription}"  TextColor="White" FontSize="16"/>
                    </Grid>
                </DataTemplate>
            </syncfusion:SfListView.SelectedItemTemplate>
            <syncfusion:SfListView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="0.4*" />
                            <RowDefinition Height="0.6*" />
                        </Grid.RowDefinitions>
                        <Label Text="{Binding BookName}" FontAttributes="Bold" TextColor="Blue" FontSize="21" />
                        <Label Grid.Row="1" Text="{Binding BookDescription}" TextColor="Teal" FontSize="15"/>
                    </Grid>
                </DataTemplate>
            </syncfusion:SfListView.ItemTemplate>
            <syncfusion:SfListView.GroupHeaderTemplate>
                <DataTemplate>
                    <Grid BackgroundColor="#E4E4E4">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <StackLayout Orientation="Horizontal" HorizontalOptions="Start"
                   VerticalOptions="Center" >
                            <Label Text="  " TextColor="Black" />
                            <Label Text="{Binding Key}" TextColor="Black"/>
                        </StackLayout>
                        <StackLayout Orientation="Horizontal" Grid.Column="1"
                   HorizontalOptions="EndAndExpand" VerticalOptions="Center">
                            <Label Text="{Binding Count}" TextColor="Blue" FontAttributes="Bold"/>
                            <Label Text=" Count " TextColor="Black" />
                        </StackLayout>
                    </Grid>
                </DataTemplate>
            </syncfusion:SfListView.GroupHeaderTemplate>
        </syncfusion:SfListView>
    </Grid>
</ContentPage>

SfListViewTestView.xaml.cs 에서 Grouping 할 key 를 정의합니다.

// 그룹핑
listView.DataSource.GroupDescriptors.Add(new GroupDescriptor()
{
	PropertyName = "BookName",
	KeySelector = (object bookInfo) =>
	{
		var item = (bookInfo as BookInfo);
		return item.BookName[0].ToString();
	}
});

위 내용에 return 으로 반환하는 값이 Grouping 할 key 값이됩니다.(현재 첫번째 문자열기준임)

결과

 

소스
https://github.com/kei-soft/MauiApp

반응형
728x90
반응형

2022.03.01 - [Xamarin_MAUI] - [.NET MAUI] Syncfusion 의 SfListView 사용하기

 

[.NET MAUI] Syncfusion 의 SfListView 사용하기

Nuget Package 관리에서 시험판 포함을 체크하고 'Syncfusion.Maui.ListView' 설치 MauiProgram.cs 에서 아래 처럼 builder.ConfigureSyncfusionListView(); 를 호출해 준다. using Syncfusion.Maui.ListView.Hos..

kjun.kr

위 SfListView 내용에이어 item 을 선택한 경우 선택한 아이템에 대한 디자인 처리 방법

SelectionBackground="Skyblue" 를 이용하여 선택한 항목의 배경색 변경

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="MauiApp1.SfListViewTestView"
             xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:syncfusion="clr-namespace:Syncfusion.Maui.ListView;assembly=Syncfusion.Maui.ListView"
             Title="SfListView"
             BackgroundColor="White">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <SearchBar 
            x:Name="filterText"
            HeightRequest="40"
            Placeholder="Search here to filter"
            TextChanged="OnFilterTextChanged"/>
        <syncfusion:SfListView
            Grid.Row="1" 
            x:Name="listView"
            ItemSize="100" 
            ItemsSource="{Binding BookInfo}"
            SelectionBackground="Skyblue">
            <syncfusion:SfListView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="0.4*" />
                            <RowDefinition Height="0.6*" />
                        </Grid.RowDefinitions>
                        <Label Text="{Binding BookName}" FontAttributes="Bold" TextColor="Blue" FontSize="21" />
                        <Label Grid.Row="1" Text="{Binding BookDescription}" TextColor="Teal" FontSize="15"/>
                    </Grid>
                </DataTemplate>
            </syncfusion:SfListView.ItemTemplate>
        </syncfusion:SfListView>
    </Grid>
</ContentPage>

SelectedItemTemplate 을 이용해 커스텀하게 배경색과 글자색 글자 크기등을 변경

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="MauiApp1.SfListViewTestView"
             xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:syncfusion="clr-namespace:Syncfusion.Maui.ListView;assembly=Syncfusion.Maui.ListView"
             Title="SfListView"
             BackgroundColor="White">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <SearchBar 
            x:Name="filterText"
            HeightRequest="40"
            Placeholder="Search here to filter"
            TextChanged="OnFilterTextChanged"/>
        <syncfusion:SfListView
            Grid.Row="1" 
            x:Name="listView"
            ItemSize="100" 
            ItemsSource="{Binding BookInfo}"
            SelectionBackground="Skyblue">
            <syncfusion:SfListView.SelectedItemTemplate>
                <DataTemplate>
                    <Grid x:Name="grid" BackgroundColor="RoyalBlue">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="0.4*" />
                            <RowDefinition Height="0.6*" />
                        </Grid.RowDefinitions>
                        <Label Text="{Binding BookName}"  FontAttributes="Bold" TextColor="Black" FontSize="25"  />
                        <Label Grid.Row="1" Text="{Binding BookDescription}"  TextColor="White" FontSize="16"/>
                    </Grid>
                </DataTemplate>
            </syncfusion:SfListView.SelectedItemTemplate>
            <syncfusion:SfListView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="0.4*" />
                            <RowDefinition Height="0.6*" />
                        </Grid.RowDefinitions>
                        <Label Text="{Binding BookName}" FontAttributes="Bold" TextColor="Blue" FontSize="21" />
                        <Label Grid.Row="1" Text="{Binding BookDescription}" TextColor="Teal" FontSize="15"/>
                    </Grid>
                </DataTemplate>
            </syncfusion:SfListView.ItemTemplate>
        </syncfusion:SfListView>
    </Grid>
</ContentPage>

https://github.com/kei-soft/MauiApp

반응형
728x90
반응형

Nuget Package 관리에서 시험판 포함을 체크하고 'Syncfusion.Maui.ListView' 설치

MauiProgram.cs 에서 아래 처럼 builder.ConfigureSyncfusionListView(); 를 호출해 준다.

using Syncfusion.Maui.ListView.Hosting;

namespace MauiApp1;

public static class MauiProgram
{
	public static MauiApp CreateMauiApp()
	{
		var builder = MauiApp.CreateBuilder();
		builder
			.UseMauiApp<App>()
			.ConfigureFonts(fonts =>
			{
				fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
				fonts.AddFont("NotoSans-Regular.ttf", "NotoSansRegular");
				fonts.AddFont("NanumBrush.ttf", "NanumBrush");
			});

		builder.ConfigureSyncfusionListView(); // SfListView 사용위함

		return builder.Build();
	}
}


ListView 에 바인딩할 Model 정의

BookInfo.cs

using System.ComponentModel;

namespace MauiApp1.Model
{
    public class BookInfo : INotifyPropertyChanged
    {
        private string bookName;
        private string bookDesc;

        public string BookName
        {
            get { return bookName; }
            set
            {
                bookName = value;
                OnPropertyChanged("BookName");
            }
        }

        public string BookDescription
        {
            get { return bookDesc; }
            set
            {
                bookDesc = value;
                OnPropertyChanged("BookDescription");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string name)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

 

ViewModel 생성 (ListView 에 바인딩될 데이터 BookInfo)

SfListViewTestViewModel.cs

using MauiApp1.Model;

using System.Collections.ObjectModel;

namespace MauiApp1.ViewModel
{
    public class SfListViewTestViewModel
    {
        private ObservableCollection<BookInfo> bookInfo;

        public ObservableCollection<BookInfo> BookInfo
        {
            get { return bookInfo; }
            set { this.bookInfo = value; }
        }
        public SfListViewTestViewModel()
        {
            bookInfo = new ObservableCollection<BookInfo>();
            bookInfo.Add(new BookInfo() { BookName = "Object-Oriented Programming in C#", BookDescription = "Object-oriented programming is a programming paradigm based on the concept of objects" });
            bookInfo.Add(new BookInfo() { BookName = "C# Code Contracts", BookDescription = "Code Contracts provide a way to convey code assumptions" });
            bookInfo.Add(new BookInfo() { BookName = "Machine Learning Using C#", BookDescription = "You will learn several different approaches to applying machine learning" });
            bookInfo.Add(new BookInfo() { BookName = "Neural Networks Using C#", BookDescription = "Neural networks are an exciting field of software development" });
            bookInfo.Add(new BookInfo() { BookName = "Visual Studio Code", BookDescription = "It is a powerful tool for editing code and serves for end-to-end programming" });
            bookInfo.Add(new BookInfo() { BookName = "Android Programming", BookDescription = "It provides a useful overview of the Android application life cycle" });
            bookInfo.Add(new BookInfo() { BookName = "iOS Succinctly", BookDescription = "It is for developers looking to step into frightening world of iPhone" });
            bookInfo.Add(new BookInfo() { BookName = "Visual Studio 2015", BookDescription = "The new version of the widely-used integrated development environment" });
            bookInfo.Add(new BookInfo() { BookName = "Xamarin.Forms", BookDescription = "It creates mappings from its C# classes and controls directly" });
            bookInfo.Add(new BookInfo() { BookName = "Windows Store Apps", BookDescription = "Windows Store apps present a radical shift in Windows development" });
        }
    }
}

 

View 생성
- 검색할 SearchBar 를 상단에 위치
- ListView 는 그 아래에 배치

SfListViewTestView.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="MauiApp1.SfListViewTestView"
             xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:syncfusion="clr-namespace:Syncfusion.Maui.ListView;assembly=Syncfusion.Maui.ListView"
             Title="SfListView"
             BackgroundColor="White">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <SearchBar x:Name="filterText"
               HeightRequest="40"
               Placeholder="Search here to filter"
               TextChanged="OnFilterTextChanged"/>
        <syncfusion:SfListView x:Name="listView" Grid.Row="1" 
                           ItemSize="100" 
                           ItemsSource="{Binding BookInfo}">
            <syncfusion:SfListView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="0.4*" />
                            <RowDefinition Height="0.6*" />
                        </Grid.RowDefinitions>
                        <Label Text="{Binding BookName}" FontAttributes="Bold" TextColor="Blue" FontSize="21" />
                        <Label Grid.Row="1" Text="{Binding BookDescription}" TextColor="Teal" FontSize="15"/>
                    </Grid>
                </DataTemplate>
            </syncfusion:SfListView.ItemTemplate>
        </syncfusion:SfListView>
    </Grid>
</ContentPage>

SfListViewTestView.xaml.cs

using MauiApp1.Model;
using MauiApp1.ViewModel;

namespace MauiApp1;

public partial class SfListViewTestView : ContentPage
{
	SearchBar searchBar = null;

	public SfListViewTestView()
	{
		InitializeComponent();

		this.BindingContext = new SfListViewTestViewModel();
	}
	
	private void OnFilterTextChanged(object sender, TextChangedEventArgs e)
	{
		searchBar = (sender as SearchBar);
		if (listView.DataSource != null)
		{
			this.listView.DataSource.Filter = FilterContacts;
			this.listView.DataSource.RefreshFilter();
		}
	}

	private bool FilterContacts(object obj)
	{
		if (searchBar == null || searchBar.Text == null)
			return true;

		var taskInfo = obj as BookInfo;
		if (taskInfo.BookName.ToLower().Contains(searchBar.Text.ToLower())
			|| taskInfo.BookDescription.ToLower().Contains(searchBar.Text.ToLower()))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}


결과 화면

소스
https://github.com/kei-soft/MauiApp

 

 

반응형
728x90
반응형

Syncfusion 의 SfDataGrid 를 사용하는데 갑자기 앱 실행시 위와 같은 팝업이 뜨기 시작했다.;
커뮤니티 버전이라 신경을 안썼는데 언제부턴가 적용이 된건지 모르겠지만 버전을 내려도 동일한 증상이 발생되었다.
(신기하게도 기존 배포된 앱들은 팝업이 뜨지 않는다.;;)

해결방법은 아래 링크로 들어가서 키를 얻어야한다.
(먼저 Syncfusion 에 가입이 되어있어야한다.)
아래 링크도 들어가 LinkedIn login 으로 로그인을하면 키가 얻어진다.
https://www.syncfusion.com/downloads/communitylicense

이제 Syncfusion 의 내계정 정보로 들어가보자

위화면에서 Get License Key 를 클릭하면 키 정보를 얻어올수 있다
그리고 아래 링크를 참고하여 코드를 추가하면 된다.

https://help.syncfusion.com/common/essential-studio/licensing/license-key

xamarin forms

public App()
{
//Register Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");

InitializeComponent();

MainPage = new App1.MainPage();
}
반응형
728x90
반응형

Syncfusion 의 SfRotator 는 아래 그림과 같이 이미지 등을 슬라이드로 보여주는 컨트롤입니다.

우선 보여줄 이미지를 준비합니다.

전 Images 폴더를 만들어 이미지를 넣었습니다.

이미지를 넣고 추가로 해야할건 각 이미지들의 속성에서 '빌드작업'을 '포함 리소스'로 변경해야합니다.

포함리소스 관련해서는 아래 포스팅 참고해주세요

2017/07/06 - [C#.NET/Xamarin] - (Xamarin Forms) 4.Image

 

이제 main1~5.jpg 그림파일을 5개를 이용해서 슬라이드 되도록 할것입니다.

우선  nuget 에서 SfRotator 를 검색해서 설치합니다.

 

아래처럼 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:syncfusion="clr-namespace:Syncfusion.SfRotator.XForms;assembly=Syncfusion.SfRotator.XForms"
             x:Class="MiGong.HomePage">
    <ContentPage.Content>
        <StackLayout>
            <syncfusion:SfRotator x:Name="rotator" NavigationStripMode="Dots"  NavigationStripPosition="Bottom"
                                   EnableAutoPlay="true" NavigationDelay="3000"/>

            <Label Text="Welcome to Xamarin.Forms!"
                VerticalOptions="CenterAndExpand"
                HorizontalOptions="CenterAndExpand" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

NavigationStripMode 는 네비게이션을 점으로 보일지 아니면 그냥 썸네일 방식으로 보여줄지 여부입니다.

NavigationStripPosition 은 네비게이션의 위치입니다.

EnableAutoPlay 는 자동으로 슬라이드가 될지 여부입니다.

NavigationDelay 는 자동으로 슬라이드되는 경우 정지될 시간입니다. (밀리초단위)

추가로 여러가지 속성이 있습니다.

아래 링크 참고해주세요

https://help.syncfusion.com/xamarin/sfrotator/overview

이제 비하인드 코드 xaml.cs 파일을 아래 처럼 작성합니다.

            List<SfRotatorItem> rotatorItem1 = new List<SfRotatorItem>();

            foreach (string imageName in new string[]{ "main1.jpg", "main2.jpg", "main3.jpg", "main4.jpg", "main5.jpg" })
            {
                SfRotatorItem item = new SfRotatorItem();
               
                Image image
                    = new Image()
                    {
                        Source = ImageSource.FromResource("MiGong.Images." + imageName),
                        Aspect = Aspect.AspectFill,
                        VerticalOptions = LayoutOptions.Center,
                        HeightRequest = 250
                        //WidthRequest = 400
                    };
               
                item.ItemContent = image;
                rotatorItem1.Add(item);
            }
            this.rotator.ItemsSource = rotatorItem1;

이제 실행해 보면 아래처럼 나타납니다.

 

 

 

반응형
728x90
반응형

Grid 를 기본 제공 되는걸 쓰는게 좋겠지만 기능과 Styling 등을 하려면 시간이 많이 소요됩니다.

그렇기 때문에 좋은 컴포넌트가 있다면 쓰는걸 선호하는 편입니다.

Grid 쪽을 찾다보니 Syncfusion 이 눈에 들어왔습니다.

https://www.syncfusion.com/products/xamarin

SfDataGrid 만을 보고 들어왔는데 정말 많은 컨트롤들이 Xamarin 에서 사용가능하도록 되어있는걸 확인 할수 있었습니다.

여기 있는 컨트롤 가지고도 개발하기엔 충분해 보이네요

단 가격이 문제입니다. 그런데 다행히도

Free Community License 라고 해서

개인개발자이거나 연매출이 1백만달러 이하고 5명이하인 회사에는 무료로 사용가능하다고 합니다.

다음에 여기 컨트롤들을 좀 가져다가 써본걸 포스팅 해봐야겠네요

차트부터 우선 궁금합니다.

이제 본론으로 들어가서 SfDataGrid 를 살펴보겠습니다.

우선 사용하기 위해선 Nuget 에서 다운을 해야하는데요

NuGet.org 가 아닌 다른 곳에서 가져와야합니다.

솔루션용 NuGet 패키지 관리로 들어가서

상단의 패키지 소스 항목 옆의 톱니바퀴(설정)를 클릭합니다.

아래와 같은 창이 나오고 우측 상단에 + 을 누르고 추가된 패키지 소스 내용을 변경합니다.

이름은 아무거나 (예: syncfusion package)

소스는 http://nuget.syncfusion.com/nuget_xamarin/nuget/getsyncfusionpackages/xamarin/

으로 설정하고 업데이트 버튼을 한번 클릭해 주고 확인하고 나갑니다.

위 작업이 완료되면 패키지 소스에 내가 추가한 소스를 선택하고 sfdatagrid 로 검색하면 아래 처럼 검색이 됩니다.

솔루션용이라 우측에 각 프로젝트를 선택하도록 되어있는데 모두 선택하고 설치를 진행합니다.

확인...

무료라 고맙다. 동의함.

이제 각 프로젝트에 참조가 추가된걸 확인할수 있습니다.

아직 준비가 끝난게 아닙니다.

Android 는 기본적으로 수행이 가능하나

iOS, UWP 코딩에 초기화하는 내용을 넣어주어야합니다. (OxyPlot 차트 했을 때와 비슷)

iOS (AppDelegate.cs)

using System;
using System.Collections.Generic;
using System.Linq;

using Foundation;
using UIKit;

namespace XamarinFormsStudy.iOS
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the
    // User Interface of the application, as well as listening (and optionally responding) to
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            OxyPlot.Xamarin.Forms.Platform.iOS.PlotViewRenderer.Init();
            Syncfusion.SfDataGrid.XForms.iOS.SfDataGridRenderer.Init();

            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }
    }
}

UWP (App.xaml.cs)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace XamarinFormsStudy.UWP
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {

#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                Xamarin.Forms.Forms.Init(e);
                OxyPlot.Xamarin.Forms.Platform.UWP.PlotViewRenderer.Init();
                Syncfusion.SfDataGrid.XForms.UWP.SfDataGridRenderer.Init();

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(typeof(MainPage), e.Arguments);
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }

        /// <summary>
        /// Invoked when Navigation to a certain page fails
        /// </summary>
        /// <param name="sender">The Frame which failed navigation</param>
        /// <param name="e">Details about the navigation failure</param>
        void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activity
            deferral.Complete();
        }
    }
}

이제 준비 작업은 완료되었습니다.

 

신규 ContentPage 를 만들어 SfDataGridPage.xaml 를 생성합니다.

SfDataGridPage.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:syncfusion="clr-namespace:Syncfusion.SfDataGrid.XForms;assembly=Syncfusion.SfDataGrid.XForms"
             x:Class="XamarinFormsStudy.SfDataGridPage">
    <ContentPage.Content>
        <StackLayout>
            <syncfusion:SfDataGrid x:Name="dataGrid" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

SfDataGridPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
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 SfDataGridPage : ContentPage
    {
        private ObservableCollection<OrderInfo> orderInfo;

        public SfDataGridPage()
        {
            InitializeComponent();

            // 바인딩될 데이터를 추가합니다.
            orderInfo = new ObservableCollection<OrderInfo>();
            orderInfo.Add(new OrderInfo(1001, "Maria Anders", "Germany", "ALFKI", "Berlin"));
            orderInfo.Add(new OrderInfo(1002, "Ana Trujilo", "Mexico", "ANATR", "México D.F."));
            orderInfo.Add(new OrderInfo(1003, "Ant Fuller", "Mexico", "ANTON", "México D.F."));
            orderInfo.Add(new OrderInfo(1004, "Thomas Hardy", "UK", "AROUT", "London"));
            orderInfo.Add(new OrderInfo(1005, "Tim Adams", "Sweden", "BERGS", "Luleå"));
            orderInfo.Add(new OrderInfo(1006, "Hanna Moos", "Germany", "BLAUS", "Mannheim"));
            orderInfo.Add(new OrderInfo(1007, "Andrew Fuller", "France", "BLONP", "Strasbourg"));
            orderInfo.Add(new OrderInfo(1008, "Martin King", "Spain", "BOLID", "Madrid"));
            orderInfo.Add(new OrderInfo(1009, "Lenny Lin", "France", "BONAP", "Marseille"));
            orderInfo.Add(new OrderInfo(1010, "John Carter", "Canada", "BOTTM", "Tsawassen"));
            orderInfo.Add(new OrderInfo(1011, "Lauro King", "UK", "AROUT", "London"));
            orderInfo.Add(new OrderInfo(1012, "Anne Wilson", "Germany", "BLAUS", "Mannheim"));
            orderInfo.Add(new OrderInfo(1013, "Alfki Kyle", "France", "BLONP", "Strasbourg"));
            orderInfo.Add(new OrderInfo(1014, "Gina Irene", "UK", "AROUT", "London"));

            // 컬럼 Sorting 활성화 여부
            this.dataGrid.AllowSorting = true;

            // 더블 클릭시 이벤트
            this.dataGrid.GridDoubleTapped += DataGrid_GridDoubleTapped;

            // 데이터 로드시 이벤트
            this.dataGrid.GridLoaded += DataGrid_GridLoaded;

            // 편집여부
            this.dataGrid.AllowEditing = true;

            // 고정 컬럼/열
            this.dataGrid.FrozenRowsCount = 2;

            // 컬럼 이동 여부
            this.dataGrid.AllowDraggingColumn = true;

            // 데이터를 바인딩합니다.
            this.dataGrid.ItemsSource = orderInfo;

        }

        /// <summary>
        /// 데이터 로드시 이벤트입니다.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGrid_GridLoaded(object sender, Syncfusion.SfDataGrid.XForms.GridLoadedEventArgs e)
        {
            ActivityIndicator indicator = new ActivityIndicator();
            indicator.IsRunning = true;
            indicator.IsVisible = true;
            indicator.BackgroundColor = Color.Gray;
            this.dataGrid.Children.Add(indicator);
            Task.Delay(2000).Wait();
            indicator.IsRunning = false;
            indicator.IsVisible = false;
        }

        /// <summary>
        /// 더블 클릭시 이벤트입니다.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGrid_GridDoubleTapped(object sender, Syncfusion.SfDataGrid.XForms.GridDoubleTappedEventsArgs e)
        {
            OrderInfo selectData = e.RowData as OrderInfo;
            DisplayAlert("Select Value", selectData.CustomerID, "OK");
        }

        /// <summary>
        /// 바인딩할 Test Class 입니다.
        /// </summary>
        class OrderInfo : INotifyPropertyChanged
        {
            private int orderID;
            private string customerID;
            private string customer;
            private string shipCity;
            private string shipCountry;

            public int OrderID
            {
                get { return orderID; }
                set { this.orderID = value; }
            }

            public string CustomerID
            {
                get { return customerID; }
                set { this.customerID = value; }
            }

            public string ShipCountry
            {
                get { return shipCountry; }
                set { this.shipCountry = value; }
            }

            public string Customer
            {
                get { return this.customer; }
                set { this.customer = value; }
            }

            public string ShipCity
            {
                get { return shipCity; }
                set { this.shipCity = value; }
            }

            public OrderInfo(int orderId, string customerId, string country, string customer, string shipCity)
            {
                this.OrderID = orderId;
                this.CustomerID = customerId;
                this.Customer = customer;
                this.ShipCountry = country;
                this.ShipCity = shipCity;
            }

            #region INotifyPropertyChanged implementation

            public event PropertyChangedEventHandler PropertyChanged;

            private void RaisePropertyChanged(String Name)
            {
                if (PropertyChanged != null)
                    this.PropertyChanged(this, new PropertyChangedEventArgs(Name));
            }

            #endregion
        }
    }
}

결과

 

위 사용한 기능 이외에도 다양한 기능들이 있습니다.

참고 링크로 확인해 주세요^^

 

참고

http://nuget.syncfusion.com/nuget_xamarin/nuget/getsyncfusionpackages/xamarin/

https://help.syncfusion.com/xamarin/sfdatagrid/getting-started

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

반응형

+ Recent posts