UWP(Universal Windows Platform) Tanıtımı — Hızlı Başlangıç

1. Xaml

1.1. XAML Tanıtımı

  • XAML Genel Bakış
  • Temel olarak görsel UI öğeleri oluşturmak için kullanılır.
  • Xaml’ın temel sözdizimi XML’e dayanır.
  • Bir namespace için takma ad tanımlama:
xmlns:controls="using:Common.Controls"
  • Namespace’te tanımlanan sınıfı kullanma:
<controls:MyControl />
  • Yeniden kullanılabilir kaynaklar(Resource),

    x:Key

<Style x:Key="TextBlock_Style" />
  • Kontrol öğelerinin Adı,

x:Name

Xaml:

<MyControl x:Name="myControl" />

C#:

private MyControl myControl;
  • Yerelleştirme

    x:Uid

<TextBlock x:Uid="sampleText" />

1.2. En Temel Kontroller(Control) – TextBlock, Button

<Page x:Class="MyPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel>
        <TextBlock Text="UWP Tanıtımı" />
        <Button Content="UWP Tanıtımı" Click="Button_Click" />
    </StackPanel>
</Page>

2. MVVM

MVVM Detaylı Tanıtım

View <=> ViewModel <=> Model

  • View mümkün olduğunca sadece UI gösterim içeriği içermeli, View büyük ölçüde Xaml dili ile tamamlanır;
  • ViewModel mümkün olduğunca iş mantığı içermemeli, bunun yerine Model’deki fonksiyonları çağırarak işlemleri tamamlamalı;
  • Model mümkün olduğunca tüm iş verilerini ve mantığını içermeli, View ve ViewModel’e bağımlılığı en aza indirmeli;

3. ViewModel ile Model Arasındaki Etkileşim

3.1. ViewModel’in Model Verilerini Kontrol Etmesi

ViewModel:

public class ViewModel
{
    private Model model;
    private ChangeA()
    {
        this.model.A = "A";
    }
}

Model:

public class Model
{
    public string A { get; set; }
    public string B { get; set; }
}

3.2. Model’in ViewModel’i Bildirmesi – event

ViewModel:

public class ViewModel
{
private Model model;
    private ChangeA()
    {
        r.BEventArgs += this.Handler;
    }
    private void Handler(object sender, EventArgs e)
    {
        AnyActions();
    }
}

Model:

public delegate void BChangedHandler(object sender, EventArgs e);

public class Model
{
    public string A { get; set; }
    private string _B;
    public string B
    {
        get { return this._B; }
        set
        {
            this._B = value;
            if (BEventArgs != null)
            {
                BEventArgs(this, new EventArgs());
            }
        }
    }
    public event BChangedHandler BEventArgs;
}

4. View ile ViewModel Arasındaki Etkileşim

4.1. Veri Bağlama

4.1.1. ViewModel’e Bağlama

View:

<TextBlock Text={Binding SampleText} />

ViewModel:

public string SampleText { get; set; }

4.1.2. Diğer Kontrollere Bağlama

View:

<TextBlock x:Name="TextBlock1" Text="SampleText" />
<Button Content="{Binding ElementName=TextBlock1, Path= Text}" />

4.1.3. DataContext Belirleme

public ViewModelClass ViewModel { get; set; }

...
SpecifiedControl.DataContext = ViewModel;
...

5. (View ile ViewModel) Bildirim Uygulama – INotifyPropertyChanged

SampleText değiştiğinde, bu property’e bağlı olan DependencyProperty’ye bildirim gönderilir

public class MyControlViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

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

        private string _sampleText;
        public string SampleText
        {
            get
            {
                return _sampleText;
            }
            set
            {
                _sampleText = value;
                Notify(nameof(SampleText));
            }
        }
    }

Veya ViewModelBase’den türetme

public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

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

6. (View ile ViewModel) ListView’ın Bildirim Uygulayan Kaynağa Bağlanması – ObservableCollection

ListView

ListView’da bildirim uygulayan bir ItemSource’a bağlanma

View:

<ListView ItemsSource="{Binding Items}">

ViewModel:

public ObservableCollection<Recording> Items { get; set; }
  • ObservableCollection sadece Item ekleme\kaldırma, tüm liste yenilenmesi durumunda bildirim üretir;
  • Eğer item Recording’ın içeriği değiştiğinde arayüzü bildirmek gerekiyorsa, Recording’ın INotifyPropertyChanged uygulaması gerekir.

7. (View) ListView’ın Öğe Şablonları(DataTemplate | UserControl)

7.1. DataTemplate

View:

<ListView ItemsSource="{Binding Items}">
    <ListView.ItemTemplate>
        <DataTemplate DataType="local:Recording">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding A}" />
                <TextBlock Text="{Binding B}" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

ViewModel:

public ObservableCollection<RecordingViewModel> Items { get; set; }

public class RecordingViewModel : INotifyPropertyChanged
{
    ...
    INotifyPropertyChanged uygulaması
    ...

    private Recording _recording;

    public string A
    {
        get
        {
            return this._recording.A;
        }
        set
        {
            this._recording.A = value;
            Notify(nameof(A));
        }
    }

    public string B { get; set; } = this._recording.B;

    public RecordingViewModel (Recording recording)
    {
        this._recording = recording;
    }
}

Model:

public class Recording
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    ... ...
}

Karşılaştırma:

ViewModel/Model Ayrımı

7.2. UserControl

7.2.1. DependencyProperty

View:

<control:MyControl Text="App is on searching" IsSearching="{Binding ViewModel.IsSearching}" />

ViewModel:

public class MyControl
{
...
public static readonly DependencyProperty IsSearchingProperty =
    DependencyProperty.Register
    (
        "IsSearching", typeof(Boolean),
        typeof(MyControl), null
    );

public bool IsSearching
{
    get { return (bool)GetValue(IsSearchingProperty); }
    set { SetValue(IsSearchingProperty, value); }
}
...
}

8. (ViewModel ile Model) Veri Dönüşümü – IValueConverter

ViewModel ve Model arasındaki veri dönüşümü için IValueConverter kullanılabilir.

public class ShowAllButtonVisibilityConverter:IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value is IList)
            {
                int count = (value as IList).Count;
                if (count > 3)
                {
                    return Windows.UI.Xaml.Visibility.Visible;
                }
            }
            return Windows.UI.Xaml.Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            if (value is IList)
            {
                int count = (value as IList).Count;
                if (count > 3)
                {
                    return Windows.UI.Xaml.Visibility.Visible;
                }
            }
            return Windows.UI.Xaml.Visibility.Collapsed;
        }

9. (View) Kontrolün Stilini Değiştirme

9.1. Kontrol İçinde Stil Belirleme

View:

<TextBlock Foreground="Red" Text="SampleText" />

9.2. Birleşik Stil Kullanma – ResourceDictionary

View:

<Window.Resources>
    <ResourceDictionary>
        <Style TargetType="TextBlock" x:Key="ImportantText">
            <Setter Property="Foreground" Value="Red" />
        </Style>
    </ResourceDictionary>
</Window.Resources>
...
<TextBlock Text="SampleText" Style={StaticResource ImportantText} />

9.3. ThemeResource Kullanma

View:

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.ThemeDictionaries>
            <ResourceDictionary x:Key="Light">
                <Style TargetType="TextBlock" x:Key="ImportantText">
                    <Setter Property="Foreground" Value="Red" />
                </Style>
            </ResourceDictionary>

            <ResourceDictionary x:Key="Dark">
                <Style TargetType="TextBlock" x:Key="ImportantText">
                    <Setter Property="Foreground" Value="Yellow" />
                </Style>
            </ResourceDictionary>

            <ResourceDictionary x:Key="HighContrast">
                <Style TargetType="TextBlock" x:Key="ImportantText">
                    <Setter Property="Foreground" Value="Black" />
                </Style>
            </ResourceDictionary>
        </ResourceDictionary.ThemeDictionaries>
    </ResourceDictionary>
</Window.Resources>
...
<TextBlock Text="SampleText" Style={ThemeResource ImportantText} />

10. Panel Kullanımı

10.1. Grid

Özellikler:

  • Varsayılan Height/Width üst öğeye eşittir;

Öneriler:

  • Grid içindeki alt öğelerin boyutlarını tanımlayın;
  • Oranlı gösterim kullanın;

10.2. StackPanel

Özellikler:

  • Üst öğe sınırlarını aşabilir;
  • Height veya Width Panel içindeki öğelere göre değişir;

Öneriler:

  • Padding ve oranları esnek kullanın;
  • Kontrol’ün sınırları aşmasını önlemek için üst öğede StackPanel’in Width veya Height’ına bir değer verin;

11. (View) Uyumlu UI (Adaptive UI)

  • VisualStateManager.VisualStateGroup kullanma
<VisualStateGroup>
    <VisualState x:Name="WideLayout">
        <VisualState.StateTriggers>
            <AdaptiveTrigger x:Name="WideLayoutTrigger" MinWindowWidth="1280" />
        </VisualState.StateTriggers>
        <VisualState.Setters>
            <Setter Target="SystemUpdateSideGrid.Width" Value="800" />
            <Setter Target="SystemUpdateSideGrid.Grid.Row" Value="0" />
        </VisualState.Setters>
    </VisualState>

    <VisualState x:Name="MidLayout">
        <VisualState.StateTriggers>
            <AdaptiveTrigger x:Name="MidLayoutTrigger" MinWindowWidth="700" />
        </VisualState.StateTriggers>
        <VisualState.Setters>
            <Setter Target="SystemUpdateSideGrid.Width" Value="400" />
            <Setter Target="SystemUpdateSideGrid.Grid.Row" Value="1" />
        </VisualState.Setters>
    </VisualState>
    ...
</VisualStateGroup>

12. Düzen Prensipleri

  • Öğe boyutlarını açıkça belirlemeyin;
  • Öğe konumunu belirlemek için ekran koordinatları kullanmayın;
  • Konteyner içindeki alt öğeler mevcut alanı paylaşır;
  • İç içe yerleştirilebilir düzen konteynerleri;

13. Yerelleştirme(Localization)

  • x:Uid kullanın, öğelerin benzersiz tanımlayıcısı
    <TextBlock x:Uid="S_TextBlock1" />
  • Resources File kullanma
    <data name="S_TextBlock1.Text" xml:space="preserve">
        <value>Örnek metin</value>
    </data>

14. İsimlendirme Yöntemleri

Büyük deve biçimi big camel-case: firstName

Küçük deve biçimi little camel-case: FirstName

  • Sınıf: big camel-case
  • Property: big camel-case
  • Alan: little camel-case ve “_” öneki ile
  • Xaml’da Kontrol: little camel-case

15. Dikkat Edilmesi Gerekenler

  • ViewModel’deki Property’leri yeniden adlandırırken dikkatli olun, çünkü Xaml’daki Binding isimleri yeniden yapılandırmayı takip etmez;