一、通过窗体中的按钮实现退出时数据保存提示
Xaml:
<Grid>
<TextBlock HorizontalAlignment="Left" Margin="152,159,0,0" TextWrapping="Wrap" Text="示例数据:" VerticalAlignment="Top" Height="20" Width="104" FontSize="18"/>
<TextBox x:Name="TextBox_ExpData" HorizontalAlignment="Left" Height="23" Margin="282,156,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="120"/>
<Button Content="退出" HorizontalAlignment="Left" Margin="448,159,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
后台:
private void Button_Click(object sender, RoutedEventArgs e)
{
if (!this.TextBox_ExpData.Text.Equals("0"))
{
MessageBoxResult result = MessageBox.Show("数据有变更,是否保存数据变更?", "WPF实例", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
MessageBox.Show("数据被保存!");
Application.Current.MainWindow.Close();
}
else if (result == MessageBoxResult.No)
{
Application.Current.MainWindow.Close();
}
else
{
return;
}
}
}
效果图:
二、通过点击右上角叉来实现数据保存提示
Xaml:
只需要在Window里面加一个Close事件,Closing="Window_Closing"
后台:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!this.TextBox_ExpData.Text.Equals("0"))
{
MessageBoxResult result = MessageBox.Show("数据有变更,是否保存数据变更?", "WPF实害例�", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
MessageBox.Show("数据被保存。");
e.Cancel = false;
}
else if (result == MessageBoxResult.No)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
else
{
e.Cancel = false;
}
}
}
效果图: