In my app i used WPF TabControl
, I want click event on TabItem
, how do i do it?
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;
}
}
hope the helping
i hope to get some simple answers as i am new to wpf
CodePudding user response:
I Made Some Changes To Your Code Which Worked Successfully As Below:
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;
}
});
}
Note:
The "Dispatcher.InvokeAsync" code prevents threads from interfering
CodePudding user response:
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;
}
}