Reputation: 1735
Am trying to prevent users from leaving a TabItem
until a condition is met.
I've implemented code on LostFocus
but it keeps firing continuously. I've tried unsubscribing to the event and then subscribing again after setting the TabItem
focus. I've also tried setting the TabItem
IsSelected
true but still none of these work.
private void dataTab_LostFocus(object sender, RoutedEventArgs e)
{
var result = MessageBox.Show("Do you want to proceed?", "No Option chosen", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
NextTab.Focus();
else {
dataTab.LostFocus -= dataTab_LostFocus;
dataTab.IsSelected = true;
//Also tried dataTab.Focus();
//e.Handled = true; Also tried.
dataTab.LostFocus +=dataTab_LostFocus;
}
}
Upvotes: 2
Views: 428
Reputation: 21969
LostFocus
is a wrong event, you have to use SelectionChanged
of TabControl
to prevent tab switching.
Below is a working solution (without MVVM logic may looks obscure). Problem is the lack of SelectionChanging
event (before SelectedItem
is changed), so you have to remember previously selected item yourself.
xaml:
<TabControl x:Name="tabControl" SelectionChanged="TabControl_SelectionChanged">
<TabItem x:Name="dataTab" Header="1" /> <!-- the tab with confirmation -->
<TabItem Header="2" />
<TabItem Header="3" />
</TabControl>
cs:
object _previous;
void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var isPreviousWasDataTab = _previous == dataTab;
_previous = tabControl.SelectedItem; // store SelectedItem for next event
if (isPreviousWasDataTab && MessageBox.Show("", "", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
_previous = tabControl.SelectedItem = dataTab;
}
Last line may require a bit explanation:
SelectedItem = dataTab
will rise SelectionChanged
event;TabControl_SelectionChanged()
will be called;isPreviousWasDataTab == false
, therefore nothing interesting happens;_previous = dataTab
.Upvotes: 2
Reputation: 6963
Wire up an event hanlder to Tabcontrol's Selection changed event.
private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e){
//do your filtering here, and set tab control item to the one you want.
Upvotes: 1