问题
hello i got a problem, whenever i try to write any simple thing inside the TabControl_SelectionChanged event i am getting this message
An unhandled exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll
Additional information: Dispatcher processing has been suspended, but messages are still being processed.
for example: this is my xaml:
<Window x:Class="try1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="auto" Width="auto" xmlns:my="clr-namespace:try1" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="171" d:DesignWidth="271" SizeToContent="WidthAndHeight">
<TabControl SelectionChanged="TabControl_SelectionChanged">
<CheckBox Name="cbx"></CheckBox>
<TabItem Header="tabItem1" Name="tabItem1">
<Grid />
</TabItem>
<TabItem Header="tabItem2" Name="tabItem2">
<Grid />
</TabItem>
</TabControl>
and this is my code behind :
private void something_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("hello");
}
thanks in advance for your help
回答1:
That's because you SelectionChanged event gets fired before the tabcontrol (and window) is loaded. If you do it like this, it works (sorry for the VB.NET sample, but you get the point):
Private Sub TabControl_SelectionChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)
If Me.IsLoaded Then
MsgBox("hello")
End If
End Sub
And yes, the reason is explained in the newsgroup post mentioned in the comment.
来源:https://stackoverflow.com/questions/4504310/selectionchanged-event-firing-exceptions-for-unknown-reasons