728x90
반응형

Visual Studio 2022 preview 17.3.0 실행
.NET MAUI 앱(미리보기) 로 프로젝트 만들기

Nuget 패키지 관리에서 시험판 포함 체크후 Plugin.Fingerprint 3.0.0-beta.1 설치

MainPage.xaml.cs 에서 지문 인증 코드 추가

using Plugin.Fingerprint;
using Plugin.Fingerprint.Abstractions;

namespace Maui.BiometricTest
{
    public partial class MainPage : ContentPage
    {
        public MainPage(IFingerprint fingerprint)
        {
            InitializeComponent();
        }

        private async void OnClicked(object sender, EventArgs e)
        {
            var request = new AuthenticationRequestConfiguration("지문인증", "지문을 인식해주세요.");

            var result = await CrossFingerprint.Current.AuthenticateAsync(request);

            if (result.Authenticated)
            {
                await DisplayAlert("지문인식 성공!", "접근가능", "OK");
            }
            else
            {
                await DisplayAlert("지문인식 실패!", "접근불가", "OK");
            }
        }
    }
}

MauiProgram.cs 에 아래 코드 추가

builder.Services.AddSingleton<MainPage>();
builder.Services.AddSingleton(typeof(IFingerprint), CrossFingerprint.Current);

using Plugin.Fingerprint;
using Plugin.Fingerprint.Abstractions;

namespace Maui.BiometricTest
{
    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("OpenSans-Semibold.ttf", "OpenSansSemibold");
                });

            builder.Services.AddSingleton<MainPage>();
            builder.Services.AddSingleton(typeof(IFingerprint), CrossFingerprint.Current);

            return builder.Build();
        }
    }
}

Platforms > Android > MainActivity.cs 에  OnCreate 코드 추가

using Android.App;
using Android.Content.PM;
using Android.OS;

using Plugin.Fingerprint;

namespace Maui.BiometricTest
{
    [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
    public class MainActivity : MauiAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            CrossFingerprint.SetCurrentActivityResolver(() => this);
        }
    }
}

AndroidManifest.xml 에 권한 추가
<uses-permission android:name="android.permission.USE_BIOMETRIC" />

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
	<application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true"></application>
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	<uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="android.permission.USE_BIOMETRIC" />
</manifest>

결과
https://www.youtube.com/shorts/bDWoIP8PHF0


소스
https://github.com/kei-soft/KJunBlog/tree/master/Maui.BiometricTest

반응형
728x90
반응형

syncfusion 의 SfBadgeView 컨트롤은 버튼이나 이미지에 벳지 숫자를 표현하고 싶을 때 사용한다.
먼저 MauiProgram.cs 에 아래처럼 builder.ConfigureSyncfusionCore(); 를추가해 준다.

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();

// SfBadgeView, SfEffectsView
builder.ConfigureSyncfusionCore();

xaml 단에서 
xmlns:syncfusionCore="clr-namespace:Syncfusion.Maui.Core;assembly=Syncfusion.Maui.Core"
를 정의하고 사용하면 된다.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="MauiApp1.SfTestView"
             xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:sys="clr-namespace:System;assembly=netstandard"
             xmlns:local="clr-namespace:MauiApp1.Defines"
             xmlns:syncfusionCore="clr-namespace:Syncfusion.Maui.Core;assembly=Syncfusion.Maui.Core"
             Title="SfTestView"
             BackgroundColor="White">

    <StackLayout Margin="10">
        <Label Text ="SfBadgeView" VerticalTextAlignment="Center" FontSize="15" FontAttributes="Bold"/>
        <syncfusionCore:SfBadgeView HorizontalOptions="Center" VerticalOptions="Center" BadgeText="20" Margin="5">
            <syncfusionCore:SfBadgeView.Content>
                <Button Text="Badge" WidthRequest="200"  HeightRequest="60" HorizontalOptions="Center"/>
            </syncfusionCore:SfBadgeView.Content>
            <syncfusionCore:SfBadgeView.BadgeSettings>
                <syncfusionCore:BadgeSettings 
                    FontSize="15" 
                    FontAttributes="Bold" 
                    FontFamily="serif" 
                    Stroke="Blue" 
                    BorderWidth="2" 
                    Type="Info" 
                    CornerRadius="5,5,5,5" 
                    Position="BottomRight">
                </syncfusionCore:BadgeSettings>
            </syncfusionCore:SfBadgeView.BadgeSettings>
        </syncfusionCore:SfBadgeView>
    </StackLayout>
</ContentPage>


BadgeSettings 에서 Badge 의 폰트 및 외곽선, 코너반지름등을 설정할수 있으며
Position 을 통해 Badge의 위치를 지정할 수 있다. 또한 Type 를 통해서 지정된 Badge 색을 불러와 사용할수 있다.
참고 : https://help.syncfusion.com/maui/badge-view/getting-started

그런데 실제 기기에 배포하면 희한하게도 아래처럼 표시된다 ㅜㅠ 원래 딱 달라붙어야하는데;;

Preview 니까 봐주자..

syncfusion 의 SfEffectsView 컨트롤은 항목에 효과를 주고 싶을 때 사용하는 컨트롤이다.
이 컨트롤 또한 사용하려면 MauiProgram.cs 에 builder.ConfigureSyncfusionCore(); 를 추가해 준다.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="MauiApp1.SfTestView"
             xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:sys="clr-namespace:System;assembly=netstandard"
             xmlns:local="clr-namespace:MauiApp1.Defines"
             xmlns:syncfusionCore="clr-namespace:Syncfusion.Maui.Core;assembly=Syncfusion.Maui.Core"
             Title="SfTestView"
             BackgroundColor="White">

    <StackLayout Margin="10">
        <Label Text ="SfBadgeView" VerticalTextAlignment="Center" FontSize="15" FontAttributes="Bold"/>
        <syncfusionCore:SfBadgeView HorizontalOptions="Center" VerticalOptions="Center" BadgeText="20" Margin="5">
            <syncfusionCore:SfBadgeView.Content>
                <Button Text="Badge" WidthRequest="200"  HeightRequest="60" HorizontalOptions="Center"/>
            </syncfusionCore:SfBadgeView.Content>
            <syncfusionCore:SfBadgeView.BadgeSettings>
                <syncfusionCore:BadgeSettings 
                    FontSize="15" 
                    FontAttributes="Bold" 
                    FontFamily="serif" 
                    Stroke="Blue" 
                    BorderWidth="2" 
                    Type="Info" 
                    CornerRadius="5,5,5,5" 
                    Position="BottomRight">
                </syncfusionCore:BadgeSettings>
            </syncfusionCore:SfBadgeView.BadgeSettings>
        </syncfusionCore:SfBadgeView>
        
        <Label Text ="SfEffectsView" VerticalTextAlignment="Center" FontSize="15" FontAttributes="Bold"/>
        <syncfusionCore:SfEffectsView 
            Margin="5"
            TouchDownEffects="Ripple">
            <Label Text ="Ripple" HeightRequest="60" VerticalTextAlignment="Center"></Label>
        </syncfusionCore:SfEffectsView>

        <syncfusionCore:SfEffectsView 
            Margin="5"
            TouchDownEffects="Rotation"
            Angle="180">
            <Label Text ="Rotation" HeightRequest="60" VerticalTextAlignment="Center"></Label>
        </syncfusionCore:SfEffectsView>
        
        <syncfusionCore:SfEffectsView 
            Margin="5"
            LongPressEffects="Selection"
            SelectionBackground="skyblue">
            <Label Text ="LongPress Selection" HeightRequest="60" VerticalTextAlignment="Center"></Label>
        </syncfusionCore:SfEffectsView>

        <syncfusionCore:SfEffectsView 
            Margin="5"
            TouchDownEffects="Ripple,Rotation"
            Angle="180">
            <Label Text ="Ripple,Rotation" HeightRequest="60" VerticalTextAlignment="Center"></Label>
        </syncfusionCore:SfEffectsView>
    </StackLayout>
</ContentPage>

아래 이미지를 보면 알겠지만 Label 이지만 선택시 효과를 주어 Ripple 로하면 선택시 둥그렇게 커지는 효과가 부여된다.
Rotation 은 말그대로 회전되는 것으로 Angle 값에 따라 회전이 된다.
Selection 은 길게 누른 경우 선택되는 효과를 줄수 있다.
TouchDownEffects 에는 여러 효과를 동시에 설정하여 사용할수 있다.

 

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

반응형
  1. 이판사판 2022.04.22 10:55

    관리자의 승인을 기다리고 있는 댓글입니다

728x90
반응형

MVVM 을 사용하기 위한 기본 구성을 정리해본다.

일단 폴더로 View, ViewModel 폴더를 만들고 ViewModel 에서 사용되는 Model 도 폴더로 생성한다.

[TestView.xaml]

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp1.TestView"
             Title="TestView">
    <StackLayout Margin="10">
        <Label Text="{Binding Title}" FontSize="20" TextColor="{x:OnPlatform iOS=Black, Android=Blue, UWP=Gray}"/>
        <Button Text="Test Command" Command="{Binding TestCommand}"/>
        <Entry x:Name="passwordEntry" IsPassword="True" Text="mvvm"/>
        <Button  Text="Param Command" Command="{Binding ParameterCommand}" CommandParameter="{Binding Source={x:Reference passwordEntry}, Path=Text}"/>
        <Entry Text="{Binding ParamValue}" />
    </StackLayout>
</ContentPage>

Parameter 가 없는 Command 는 TestCommand

Parameter 가 있는 Command 는 ParameterCommand 로 CommandParameter 에 passwordEntry 값을 사용한다.

[TestView.xaml.cs]

using MauiApp1.ViewModel;

namespace MauiApp1;

public partial class TestView : ContentPage
{
	public TestView()
	{
		InitializeComponent();

		this.BindingContext = new TestViewModel();
	}
}​

 

ViewModel 정의

using System.ComponentModel;
using System.Windows.Input;

namespace MauiApp1.ViewModel;

internal class TestViewModel : INotifyPropertyChanged
{
    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    #region Command
    public ICommand TestCommand { get; private set; }
    public ICommand ParameterCommand { get; private set; }
    #endregion

    #region Field
    private string title = "MVVM Test";
    private string paramValue = "";
    #endregion

    #region Properties
    /// <summary>
    /// 타이틀
    /// </summary>
    public string Title
    {
        get { return this.title; }
        set
        {
            this.title = value;
            OnPropertyChanged("Title");
        }
    }

    /// <summary>
    /// 파라미터 값
    /// </summary>
    public string ParamValue
    {
        get { return this.paramValue; }
        set
        {
            this.paramValue = value;
            OnPropertyChanged("ParamValue");
        }
    }
    #endregion

    // Constructor
    #region  TestViewModel
    /// <summary>
    /// TestViewModel
    /// </summary>
    public TestViewModel()
    {
        this.TestCommand = new Command(OnTestCommand);
        this.ParameterCommand = new Command<string>(OnParameterCommand);
    }
    #endregion

    // Methods
    #region OnTestCommand
    private void OnTestCommand()
    {
        App.Current.MainPage.DisplayAlert("Test", "Test Command Click.", "OK");
    }
    #endregion

    #region OnParameterCommand(string param)
    private void OnParameterCommand(string param)
    {
        this.ParamValue = param;
    }
    #endregion
}

Title 데이터 'MVVM Test'가 화면에 표시되고 Test Command 버튼 클릭시 팝업 표시된다.
Param Command 를 클릭하면 버튼위쪽 비밀번호 입력한 항목이 Parameter 로 전달되어 버튼 아래에 있는 Entry 에 표시된다.

 

반응형
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
반응형

Handler 는 기존에 사용하던 Renderer 와 비슷한데
Renderer 는 각 기기 특성을 타는 부분을 각각의 Android, iOS 프로젝트에 네이티브 코드로 처리를 할수 있도록 했다
그런데 Handler 는 이를 하나의 파일에서 처리 가능하도록 했다

Android 에서 Entry 컨트롤에 언더라인이 생기게 되는데 이를 없애려면
기존에는 아래처럼 Renderer 를 이용해서 없애야했다.

Renderer 사용예시

using Android.Content;
using Android.Graphics.Drawables;

using APP.Controls;
using APP.Droid.Renderers;

using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace APP.Droid.Renderers
{
    public class CustomEntryRenderer : EntryRenderer
    {
        public CustomEntryRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
                //Control.SetBackground(null);
            }

            if (Control != null)
            {
                GradientDrawable gd = new GradientDrawable();
                gd.SetColor(global::Android.Graphics.Color.Transparent);
                Control.SetBackground(gd);
            }
        }
    }
}​

하지만 Handler 를 이용하면 아래 처럼 간단하게 언더라인을 제거 할수 있다.

MauiProgram.cs

#if ANDROID
		// Entry 에서 언더라인 제거
		Microsoft.Maui.Handlers.EntryHandler.EntryMapper.AppendToMapping("NoUnderline", (h, v) =>
		{
			h.NativeView.BackgroundTintList = ColorStateList.ValueOf(Colors.Transparent.ToAndroid());
		});
#endif

그런데 Handler 는 익숙해지는데 시간이 걸릴것 처럼 생겨먹었다;;

ButtonHandler 등등 각컨트롤에 대해서 처리가 가능하고 직접 만든 컨트롤도 지정이 가능한것 같다

이는 추후 더 조사하고 테스트 해봐야겠다


* 추가

Entry 의 글자 색을 기기별로 바꾸고 싶을때는 아래처럼 사용한다.

		// 기기에 따른 색상 변경
		Microsoft.Maui.Handlers.EntryHandler.EntryMapper.AppendToMapping(nameof(IView.Background), (handler, view) =>
		{
			if (view is Entry)
			{
#if ANDROID
				handler.NativeView.SetTextColor(Colors.Red.ToNative());
#elif IOS
				handler.NativeView.TextColor = Colors.Yellow.ToNative();
#elif WINDOWS
				handler.NativeView.Foreground = Colors.Green.ToNative();
#endif
			}
		});

반응형
728x90
반응형

x:Reference 는 다른 컨트롤의 값을 사용하고자 할때 사용된다.

Slider 가 있고 Slider 의 Value 값을 Label 컨트롤에 표현해 주려면 아래처럼 처리하면 된다.

  <Slider x:Name="slider" Minimum="0" Maximum="100" Value="0" Background="Gray"/>
        <Label  
            Text="{Binding Source={x:Reference slider}, Path=Value}"
            VerticalOptions="CenterAndExpand" 
            HorizontalOptions="CenterAndExpand"/>

사용하면서 느낀건데 자동화 처리가 잘 안되고 핫리로드도 잘 안된다.ㅜㅠ
다시 실행해야 적용이 되는데 Xamarin 때와 달라진게 없다;

반응형
728x90
반응형

C# 코드에 정의된 static 필드를 xaml 단에서 사용할때 사용하는것이 x:static 태그이다

먼저 static 필드 정의

namespace MauiApp1.Defines;

public static class Constants
{
    public static readonly string SfListViewTitle = "SfListView Test";
}

xaml 단에서 사용

<ContentPage x:Class="MauiApp1.SfListViewTestView"
             xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             ......
             xmlns:local="clr-namespace:MauiApp1.Defines"
             .......>
        <Label 
               Text="{x:Static local:Constants.SfListViewTitle}"
               HorizontalOptions="Center" 
               Margin="5">
        </Label>
...
</ContentPage>

staticExtension 이라고 확장을 통해 사용도 가능하지만 위 일반적인 방법이 인텔리센스가 사용가능해 코딩하기 편한것 같다.
또한, 필드 명이 바뀐경우 자동으로 바꿔주고 만약 xaml 단이 바뀌지 않은 경우 오류도 도출하기 때문에 관리하기가 용이하다.

반응형
728x90
반응형

Android, iOS 에 따라서 코드 분기가 필요할때가 있다 Xamarin 에서도 기기적 특성으로 인해

사용한적이 많았는데 이부분은 Xamarin 껄 그대로 가져왔다.

xaml  단에서 사용방법은 OnPlatform 태그를 사용
( <OnPlatform> 테그를 쓰거나 직접 값을 지정할때 x:OnPlatform 을 사용하는 방식 )

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp1.NewPage"
             xmlns:syncfusion="clr-namespace:Syncfusion.Maui.ListView;assembly=Syncfusion.Maui.ListView"
             Title="NewPage"
             Padding="10,10,10,100"
             BackgroundColor="White">
    <ContentPage.Padding>
        <OnPlatform x:TypeArguments="Thickness">
            <On Platform="iOS" Value="0, 10, 0, 0" />
            <On Platform="Android" Value="10, 10, 10, 10" />
        </OnPlatform>
    </ContentPage.Padding>
    <StackLayout >
        <StackLayout.Margin>
            <OnPlatform x:TypeArguments="Thickness">
                <On Platform="iOS" Value="0, 10, 0, 0" />
                <On Platform="Android" Value="10, 10, 10, 10" />
            </OnPlatform>
        </StackLayout.Margin>
        <Label Text="Kei Soft 강준 (https://github.com/kei-soft)"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" 
                TextColor="{x:OnPlatform iOS=Black, Android=Blue, UWP=Gray}"/>
        <Button x:Name="sfListViewButton" Text="SfListView" Clicked="sfListViewButton_Clicked"/>
    </StackLayout>
</ContentPage>

 

C# Code 는 Device.RuntimePlatform 으로 구분

        if (Device.RuntimePlatform == Device.Android)
        {
            Padding = new Thickness(0, 10, 0, 0);
        }
        else if (Device.RuntimePlatform == Device.iOS)
        {
            Padding = new Thickness(10, 10, 10, 10);
        }
반응형
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

 

 

반응형

+ Recent posts