在TabControl
中有3个标签:
Tab1
包含"下一个"按钮。TabControl
设置为显示Tab2
并启动计时器(2秒)TabControl
设置为显示Tab3
。如果包含TabControl
的窗口在#3发生时没有焦点,它将在收到焦点时切换回显示Tab2
。为什么呢?
MainWindow
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void NextBtn_Click(object sender, RoutedEventArgs e)
{
DoStuff();
}
private async void DoStuff()
{
MainTabControl.SelectedItem = Tab2;
await Task.Factory.StartNew((Action)(() =>
{
Thread.Sleep(2000);
}));
MainTabControl.SelectedItem = Tab3;
}
}
}
WPF代码:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Topmost="True">
<TabControl Name="MainTabControl">
<TabItem Name="Tab1">
<TabItem.Header>
<TextBlock Text="Tab 1" />
</TabItem.Header>
<StackPanel>
<TextBlock Text="Tab 1 content" />
<Button Name="NextBtn" Click="NextBtn_Click" Content="Next tab" Width="50" HorizontalAlignment="Right" />
</StackPanel>
</TabItem>
<TabItem Name="Tab2">
<TabItem.Header>
<TextBlock Text="Tab 2" />
</TabItem.Header>
<StackPanel>
<TextBlock Text="Tab 2 content" />
</StackPanel>
</TabItem>
<TabItem Name="Tab3">
<TabItem.Header>
<TextBlock Text="Tab 3" />
</TabItem.Header>
<StackPanel>
<TextBlock Text="Tab 3 content" />
</StackPanel>
</TabItem>
</TabControl>
</Window>
答案 0 :(得分:1)
我用Snoop对你的程序进行了调试,当你打电话给我时,我看到了
MainTabControl.SelectedItem = Tab3;
并且您将焦点放在其他窗口中,tab2是聚焦所以当您选择程序的窗口时,会显示tab2。
我修复了它添加第二行:
MainTabControl.SelectedItem = Tab3;
((TabItem) MainTabControl.SelectedItem).Focus();
我希望这可以帮到你。