程序界面:
源代码:
MainWindow.xaml
<Window x:Class="WPFTabControl.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WPF TabControl" Height="240" Width="320" WindowStartupLocation="CenterScreen"> <Grid> <TabControl Name="tabControl1" SelectionChanged="tabControl1_SelectionChanged"> <TabItem Name="tabItem0" Header="TabItem0"> <Grid Background="#FFE5E5E5"/> </TabItem> <TabItem Name="tabItem1" Header="TabItem1"> <Grid Background="#FFE5E5E5"/> </TabItem> </TabControl> </Grid> </Window>
MainWindow.xaml.cs
/* ---------------------------------------------------------- * 文件名称:MainWindow.xaml.cs * * 作者:秦建辉 * * QQ:36748897 * * 博客:http://www.firstsolver.com/wordpress/ * * 开发环境: * Visual Studio V2013 * .NET Framework 4.5 * * 版本历史: * V1.0 2014年07月05日 * 解决TabControl页面切换时弹出MessageBox后引发的Bug * * 参考资料: * http://stackoverflow.com/questions/7327036/tabcontrol-preventing-user-from-changing-the-selected-tab-messagebox-causing-b * http://social.msdn.microsoft.com/Forums/en-US/7bf500ad-0f6f-4a89-8d03-92e03daa2ae8/tabcontrol-selectionchanged-strange-behaviour?forum=wpf ------------------------------------------------------------ */ using System; using System.Windows; using System.Windows.Controls; namespace WPFTabControl { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private bool IsInnerChange = false; private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (IsInnerChange) { // 内部改变 IsInnerChange = false; return; } else { int SelectedIndex = tabControl1.SelectedIndex; if (SelectedIndex == 1) { MessageBoxResult result = MessageBox.Show(this, "Are you sure to leave?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { // 检测选择页面是否因弹出MessageBox后出现变化 if (tabControl1.SelectedIndex != 1) { IsInnerChange = true; // 标记为内部改变 tabControl1.SelectedIndex = 1; } } else { // 阻止页面切换 Application.Current.Dispatcher.BeginInvoke((Action)delegate { tabControl1.SelectedIndex = 0; tabItem0.Focus(); }); } } } } } }