wpf 如何创建TabControl点击事件?[已关闭]

lx0bsm1f  于 2022-12-27  发布在  其他
关注(0)|答案(2)|浏览(322)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

昨天关门了。
Improve this question
在我的应用中,我使用了WPF TabControl,我想点击TabItem上的事件,我该怎么做?
XAML:

<TabControl 
  SelectionChanged="TabControl_SelectionChanged"
  TabStripPlacement="Left">
  <TabItem Header="Grass" x:Name="Tab1"></TabItem>
  <TabItem Header="Tree" x:Name="Tab2"></TabItem>
  <TabItem Header="Flower" x:Name="Tab3"></TabItem>
</TabControl>

C#

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
            string Tabitem = ((sender as TabControl).SelectedItem as TabItem).Header as string;
            switch (Tabitem)
            {
                case "Tab1":
                    MessageBox.Show("you chose Grass");
                    break;
                case "Tab2":
                    MessageBox.Show("you chose Tree");
                    break;
                case "Tab3":
                    MessageBox.Show("you chose Flower");
                    break;
                default:
                    return;
             }
}

希望你能帮忙。
我希望得到一些简单的答案,因为我是新的WPF。

6tr1vspr

6tr1vspr1#

我做了一些更改,以您的代码成功工作如下:

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Dispatcher.InvokeAsync(() =>
    {
        string Tabitem = ((sender as TabControl).SelectedItem as TabItem).Name as string;
        switch (Tabitem)
        {
            case "Tab1":
                MessageBox.Show("you chose Grass");
                break;
            case "Tab2":
                MessageBox.Show("you chose Tree");
                break;
            case "Tab3":
                MessageBox.Show("you chose Flower");
                break;
            default:
                return;
        }

    });
}
    • 注:**

Dispatcher.InvokeAsync "代码可防止线程干扰

bq3bfh9z

bq3bfh9z2#

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
         string Tabitem = tabControl1.SelectedTab.Text;
         switch (Tabitem)
         {
            case "Tab1":
                MessageBox.Show("you chose Grass");
            break;

            case "Tab2":
            MessageBox.Show("you chose Tree");
            break;

            case "Tab3":
                MessageBox.Show("you chose Flower");
            break;

            default:
                return;
         }
    }

相关问题