UWP(نظام Windows الأساسي الشامل) — مقدمة وبدء الاستخدام السريع

1. Xaml

1.1. مقدمة في XAML

  • XAML 概述
  • تُستخدم بشكل أساسي لإنشاء عناصر واجهة المستخدم المرئية.
  • يعتمد التركيب الأساسي لـ Xaml على XML.
  • الإعلان عن اسم مستعار لمساحة الاسم (Namespace):
xmlns:controls="using:Common.Controls"
  • استخدام الفئات المعلنة في مساحة الاسم:
<controls:MyControl />
  • موارد قابلة لإعادة الاستخدام (Resource)،

    x:Key

<Style x:Key="TextBlock_Style" />
  • اسم عنصر التحكم،

x:Name

Xaml:

<MyControl x:Name="myControl" />

C#:

private MyControl myControl;
  • الترجمة (Localization)

    x:Uid

<TextBlock x:Uid="sampleText" />

1.2. عناصر التحكم الأساسية (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 Introduction" />
        <Button Content="UWP Introduction" Click="Button_Click" />
    </StackPanel>
</Page>

2. MVVM

MVVM 详细介绍

View <=> ViewModel <=> Model

  • يجب أن يحتوي “العرض” (View) على محتوى عرض واجهة المستخدم فقط، ويتم إكمال “العرض” (View) في الغالب باستخدام لغة Xaml؛
  • يجب ألا يحتوي “نموذج العرض” (ViewModel) على منطق معالجة الأعمال قدر الإمكان، بل يكمل الإجراءات عن طريق استدعاء الوظائف الموجودة في “النموذج” (Model)؛
  • يجب أن يحتوي “النموذج” (Model) على جميع بيانات الأعمال والمنطق قدر الإمكان، وحاول عدم الاعتماد على “العرض” (View) و “نموذج العرض” (ViewModel)؛

3. التفاعل بين ViewModel و Model

3.1. تحكم ViewModel في بيانات Model

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 بإبلاغ ViewModel – 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 و ViewModel

4.1. ربط البيانات (Data Binding)

  • 数据绑定概述
  • يمكن ربط DependencyProperty فقط
  • الربط في الخاصية (Property) العامة (Public)
  • كن حذرًا عند إعادة الهيكلة (Refactoring)

4.1.1. الربط في ViewModel

View:

<TextBlock Text={Binding SampleText} />

ViewModel:

public string SampleText { get; set; }

4.1.2. الربط في Control آخر

View:

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

4.1.3. تحديد DataContext

public ViewModelClass ViewModel { get; set; }

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

5. (View و ViewModel) تنفيذ إشعار الرسائل – INotifyPropertyChanged

عندما تتغير SampleText، سيتم إخطار DependencyProperty المرتبط بهذه الخاصية (property)

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

أو الوراثة من ViewModelBase

public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

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

6. (View و ViewModel) ربط ListView بمصدر يدعم إشعار الرسائل – ObservableCollection

ListView

تنفيذ الربط إلى ItemSource الذي يحتوي على إشعارات في ListView

View:

<ListView ItemsSource="{Binding Items}">

ViewModel:

public ObservableCollection<Recording> Items { get; set; }
  • ترسل ObservableCollection إشعارات فقط عند إضافة عنصر \ إزالته، أو عند تحديث القائمة بالكامل؛
  • إذا كنت بحاجة إلى إخطار الواجهة عند تغير محتوى العنصر Recording، فيجب أن يقوم Recording بتطبيق INotifyPropertyChanged.

7. (View) قالب Item الخاص بـ ListView (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
    ...

    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; }
    ... ...
}

مقارنة:

分离 ViewModel/Model

7.2. UserControl

7.2.1. DependencyProperty

  • Dependency Properties Overview
  • يمكن فقط ربط DependencyProperty بخاصية (property) أخرى، ويمكن للربط فقط تنفيذ إخطار الرسائل إلى العرض (View)
  • له أولوية

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 و Model) تحويل البيانات – IValueConverter

يمكن استخدام IValueConverter لتحويل البيانات بين ViewModel و Model.

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) تعديل نمط (Style) عنصر التحكم (Control)

9.1. تخصيص النمط داخل عنصر التحكم

View:

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

9.2. استخدام نمط موحد – 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

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

10.1. شبكة (Grid)

المميزات:

  • الارتفاع/العرض الافتراضي يساوي العنصر الأصل؛

الاقتراحات:

  • تحديد حجم تخطيط العناصر الفرعية في Grid؛
  • العرض بالنسب المئوية؛

10.2. StackPanel

المميزات:

  • يمكن أن يتجاوز حدود العنصر الأصل؛
  • يتغير الارتفاع أو العرض حسب العناصر الموجودة داخل Panel؛

الاقتراحات:

  • استخدم Padding والنسب بمرونة؛
  • أعطِ قيمة للعرض (Width) أو الارتفاع (Height) لعنصر StackPanel في العنصر الأصل، لمنع تجاوز عنصر التحكم للحدود؛

11. (View) واجهة المستخدم التكيفية (Adaptive UI)

  • استخدام VisualStateManager.VisualStateGroup
<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. مبادئ التخطيط

  • لا تقم بتعيين أبعاد العناصر بشكل صريح؛
  • لا تستخدم إحداثيات الشاشة لتحديد موضع العناصر؛
  • تشارك العناصر الفرعية داخل الحاوية المساحة المتاحة؛
  • حاويات التخطيط قابلة للتعشيش؛

13. الترجمة (Localization)

  • استخدام x:Uid، المعرف الفريد للعنصر
    <TextBlock x:Uid="S_TextBlock1" />
  • استخدام ملف الموارد (Resources File)
    <data name="S_TextBlock1.Text" xml:space="preserve">
        <value>Sample text</value>
    </data>

14. اصطلاحات التسمية

حالة الجمل الكبيرة big camel-case: firstName

حالة الجمل الصغيرة little camel-case: FirstName

  • الفئة (Class): حالة الجمل الكبيرة
  • الخاصية (Property): حالة الجمل الكبيرة
  • الحقل (Field): حالة الجمل الصغيرة مع بادئة “_”
  • عنصر التحكم (Control) في Xaml: حالة الجمل الصغيرة

15. ملاحظات

  • كن حذرًا عند إعادة تسمية الخاصية (Property) في ViewModel، لأن اسم الربط (Binding) في Xaml لن يتبع إعادة الهيكلة (Refactoring)؛