UWP(Universal Windows Platform)介绍 — 快速上手
Categories:
- 1. Xaml
- 2. MVVM
- 3. ViewModel 与 Model 的交互
- 4. View 与 ViewModel 的交互
- 5. (View 与 ViewModel) 实现消息通知 – INotifyPropertyChanged
- 6. (View 与 ViewModel) ListView 绑定到实现了消息通知的源 – ObservableCollection
- 7. (View) ListView 的 Item 模板(DataTemplate | UserControl)
- 8. (ViewModel 与 Model) 数据转换 – IValueConverter
- 9. (View) 修改 Control 的 Style
- 10. 使用 Panel
- 11. (View) 自适应 UI (Adaptive UI)
- 12. 布局原则
- 13. 本地化(Localization)
- 14. 命名方式
- 15. 注意
1. Xaml
1.1. XAML 简介
- XAML 概述
- 主要用于创建可视的 UI 元素.
- Xaml 的基本语法基于 XML.
- 声明一个 namespace 的别名:
xmlns:controls="using:Common.Controls"
- 使用 namespace 中声明的类:
<controls:MyControl />
可重用的资源(Resource),
x:Key
<Style x:Key="TextBlock_Style" />
- 控件元素的 Name,
x:Name
Xaml:
<MyControl x:Name="myControl" />
C#:
private MyControl myControl;
本地化
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

- View 尽量只包含 UI 展示的内容, 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. 数据绑定
- 数据绑定概述
- 只有 DependencyProperty 可以被绑定
- 绑定在 Public 的 Property
- 谨慎重构
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 发生变化时, 会通知到绑定在该 property 的 DependencyProperty
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
View:
<ListView ItemsSource="{Binding Items}">
ViewModel:
public ObservableCollection<Recording> Items { get; set; }
- ObservableCollection 只在 Item 添加\移除, 整个列表刷新时才产生消息通知;
- 如果需要在 item Recording 的内容发生变化时通知界面, 需要由 Recording 实现 INotifyPropertyChanged.
7. (View) ListView 的 Item 模板(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
{
...
Implement 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; }
... ...
}
比较:

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) 修改 Control 的 Style
9.1. 在 Control 里定制 Style
View:
<TextBlock Foreground="Red" Text="SampleText" />
9.2. 使用统一的 Style – 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
特点:
- 默认 Height/Width 等于父级元素;
建议:
- 在 Grid 中定义子元素的布局大小;
- 以比例显示;
10.2. StackPanel
特点:
- 可以超越父元素边界;
- Height 或 Width 随 Panel 内的元素变化;
建议:
- 灵活使用 Padding 和比例;
- 在父级元素给 StackPanel 的 Width 或 Height 一个值, 以防止 Control 越界;
11. (View) 自适应 UI (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: big camel-case
- Property: big camel-case
- Field: little camel-case with prefix “_”
- Control in Xaml: little camel-case
15. 注意
- 谨慎重命名 ViewModel 中的 Property, 因为 Xaml 中的 Binding 名称不会跟随重构;