Of course, not all child controls will have an event handler or even need one (e.g. a ComboBox bound to a property of a Business Entity). Moreover, the parent control can not depend on the implementation of his children. Fortunately the parent control can decide to ignore all bubbled events from child controls like this:
///
<summary>
///
The selection in the main tab control was changed.
///
</summary>
///
<param name="sender">
Sender of the event: the Main Tab.
</param>
///
<param name="e">
Event arguments.
</param>
private
void
MainTabControl_SelectionChanged(
object
sender,
SelectionChangedEventArgs
e)
// Ignore Routed Events from children
if
(e.OriginalSource ==
this
.MainTabControl)
// First Tab
if
(
this
.MainTabControl.SelectedIndex == 0)
// (Re-)Populate ListBox
this
.ListBox1.Items.Clear();
this
.ListBox1.Items.Add(
"Building Windows Applications with WPF, LINQ and WCF"
);
this
.ListBox1.Items.Add(
"Building Cloud based Enterprise Applications for Windows Azure"
);
this
.ListBox1.Items.Add(
"Designing Data Warehouses using Dimensional Modeling"
);
this
.ListBox1.Items.Add(
"Upgrade to SharePoint 2010"
);
// Select first item (no more 'Kaboom')
this
.ListBox1.SelectedIndex = 0;
In practice this means that you should program this check on
OriginalSource
not only in every TabControl (because its TabItems can contain ListBoxes and ComboBoxes), but also in every ListBox (because its template can contain ComboBoxes).
Thanks, your article is very useful.
Reply DeleteThank you, well described and very useful.
Reply DeleteThanks! I used "if(sender == e.OriginalSource)" instead, in order to recycle the method.
Reply Deletethanks, how to do that in xaml for mvvm?
Reply DeleteThis is a very helpful explanation and demonstration.
Reply Delete