上一篇提到了基于代理(委托)的编程,这里说一下基于事件的编程。其实基于事件的编程和基于代理的编程差不多,可以说是基于代理编程的2.0版本,但是基于事件编程有一个很大的改进,那就是支持多播。
下面是一个小例子,点击按钮之后5S之后获取系统时间并且显示出来。
<phone:PhoneApplicationPage
x:Class="EventTask.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot 是包含所有页面内容的根网格-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- 本地化说明:
若要本地化显示的字符串,请将其值复制到应用程序的非特定语言资源文件(AppResources.resx)
中的适当命名的键,然后
将属性的引号之间的硬编码文本值
替换为其路径指向该字符串名称的绑定子句。
例如:
Text="{Binding Path=LocalizedResources.ApplicationTitle, Source={StaticResource LocalizedStrings}}"
此绑定指向模板的名为“ApplicationTitle”的字符串资源。
在“项目属性”选项卡中添加受支持的语言将会为
每种语言创建一个新的 resx 文件,该文件可以包含 UI 字符串的翻译值
。这些示例中的绑定将导致在运行时从
与应用程序的 CurrentUICulture 匹配的 .resx 文件中
提取属性的值。
-->
<!--TitlePanel 包含应用程序的名称和页标题-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"/>
<!--ContentPanel - 在此处放置其他内容-->
<Button Content="显示时间" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="166,293,0,0" Grid.Row="1" RenderTransformOrigin="0.548,1.459" Click="Button_Click"/>
<!--取消注释,以显示对齐网格,从而帮助确保
控件在公用边界上对齐。图像在系统栏中显示时的
上边距为 -32px。如果隐藏了系统栏,则将此值设为 0
(或完全删除边距)。
在发送之前删除此 XAML 和图像本身。-->
<!--<Image Source="/Assets/AlignmentGrid.png" VerticalAlignment="Top" Height="800" Width="480" Margin="0,-32,0,0" Grid.Row="0" Grid.RowSpan="2" IsHitTestVisible="False" />-->
</Grid>
</phone:PhoneApplicationPage>
下面是控制类和code behind之间沟通的类,负责传递数据,要继承EventArgs类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventTask
{
/// <summary>
/// 自定义传递事件
/// </summary>
public class StateChangedEventArgs : EventArgs
{
public DateTime Time { get; set; }
public StateChangedEventArgs(DateTime d)
{
Time = d;
}
}
}
下面是code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using EventTask.Resources;
namespace EventTask
{
public partial class MainPage : PhoneApplicationPage
{
private ShowTimeTask task;
// 构造函数
public MainPage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
task = new ShowTimeTask();
task.StateChangedEvent += ShowTime;
// 调用方法获得当前系统事件,当调用完毕之后调用ShowTime方法
task.GetTime();
}
private void ShowTime (ShowTimeTask sender, StateChangedEventArgs args)
{
DateTime now = args.Time;
MessageBox.Show(now.ToString());
}
}
}
然后就是我们的控制类(获取系统时间):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EventTask
{
public class ShowTimeTask
{
// 委托
public delegate void StateChanged(ShowTimeTask sender, StateChangedEventArgs args);
// 定义事件
public event StateChanged StateChangedEvent;
public void GetTime()
{
if (StateChangedEvent != null)
{
DateTime time = DateTime.Now;
Thread.Sleep(5000);
StateChangedEvent(this, new StateChangedEventArgs(time));
}
}
}
}
注意上面的写法就行了。一定要注意在ShowTimeTask里面代理的参数。上面GetTime函数是该类的逻辑核心。