控件 xaml
控件 cs
using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;namespace neihan8.Control{ public partial class Toast : UserControl { public Toast() { InitializeComponent(); } public static readonly DependencyProperty MessageProperty = DependencyProperty.Register("Message", typeof(string), typeof(Toast), new PropertyMetadata(OnMessageChanged)); public string Message { get { return (string)GetValue(MessageProperty); } set { SetValue(MessageProperty, value); } } private static void OnMessageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d != null && d is Toast) { (d as Toast).SetMessage((string)e.NewValue); } } private void SetMessage(string toastBox) { message.Text = toastBox; } }}
调用控件的类
using System;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Ink;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using neihan8.Control;using System.Windows.Controls.Primitives;using System.Windows.Threading;namespace neihan8{ public class ToastPrompt { public event EventHandler Click; public event EventHandler Completed; public void Show(string message) { Popup p = new Popup(); Toast tb = new Toast() { Message = message }; p.Child = tb; p.IsOpen = true; tb.Open.Begin(); DispatcherTimer timer = new DispatcherTimer(); tb.Open.Completed += new EventHandler((sender, eventargs) => { timer.Interval = TimeSpan.FromSeconds(3); timer.Tick += new EventHandler((sd, ea) => { if (timer != null && timer.IsEnabled) { timer.Stop(); tb.Close.Begin(); } }); timer.Start(); }); tb.Close.Completed += new EventHandler((s, e) => { p.IsOpen = false; if (Completed != null) Completed.Invoke(this, new EventArgs()); }); tb.Tap += new EventHandler((sender, eventargs) => { if (Click != null) Click.Invoke(this, new EventArgs()); }); tb.ManipulationCompleted += new EventHandler ((sender, eventargs) => { if (eventargs.TotalManipulation.Translation.X > 200 || eventargs.FinalVelocities.LinearVelocity.X > 1000) { if (timer != null && timer.IsEnabled) { timer.Stop(); tb.Close.Begin(); } } }); } }}
类支持 Completed、Click 事件,支持右划关闭控件
按返回键两次退出程序事例
private bool canexit = false; public MainPage() { InitializeComponent(); this.BackKeyPress += new EventHandler(MainPage_BackKeyPress); } private void MainPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e) { e.Cancel = !canexit; ToastPrompt toast = new ToastPrompt(); toast.Completed += (o, ex) => { canexit = false; }; toast.Show("再按一次退出程序。"); canexit = true; }