首先需要设计一个简单的界面,一个label和button,如图所示。
UI核心代码如下:
<Grid>
<Label x:Name="lb_content" Content="Label" HorizontalAlignment="Left" Margin="76,68,0,0" VerticalAlignment="Top" Height="126" Width="322" FontSize="16"/>
<Button x:Name="bt_submit" Content="确定" HorizontalAlignment="Left" Margin="204,222,0,0" VerticalAlignment="Top" Width="74" Click="Bt_submit_Click"/>
</Grid>
交互逻辑代码如下:
/// <summary>
/// DiyMessageBox.xaml 的交互逻辑
/// </summary>
public partial class DiyMessageBox : Window
{
private int count = 0;
private System.Threading.Timer timer;
/// <summary>
///
/// </summary>
/// <param name="content">显示内容</param>
public DiyMessageBox(string content)
{
InitializeComponent();
lb_content.Content = content;
//居中弹出
this.Left = System.Windows.SystemParameters.PrimaryScreenWidth / 2 - this.Width / 2;
this.Top = System.Windows.SystemParameters.PrimaryScreenHeight / 2 - this.Height / 2;
}
/// <summary>
///
/// </summary>
/// <param name="content">显示内容</param>
/// <param name="count">计数值</param>
public DiyMessageBox(string content, int count)
{
InitializeComponent();
lb_content.Content = content;
this.count = count;
timer = new System.Threading.Timer(TimerFunction, null, 0, 1000);
//居中弹出
this.Left = System.Windows.SystemParameters.PrimaryScreenWidth / 2 - this.Width / 2;
this.Top = System.Windows.SystemParameters.PrimaryScreenHeight / 2 - this.Height / 2;
}
private void TimerFunction(object state)
{
Console.WriteLine(count);
this.Dispatcher.Invoke(new Action(() => { bt_submit.Content = $"确定({count})"; }));
if (count < 0)
{
timer.Dispose();
this.Dispatcher.Invoke(new Action(() => { this.Close(); }));
}
count--;
}
private void Bt_submit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}