WPF强制用户留在TabItem

时间:2016-06-07 12:14:03

标签: c# wpf

我试图阻止用户在满足条件之前离开TabItem。 我在LostFocus上实现了代码,但它一直在持续触发。我已经尝试取消订阅该活动,然后在设置TabItem焦点后再次订阅。我也试过设置TabItem IsSelected为真,但仍然没有这些工作。

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;
            }
}

2 个答案:

答案 0 :(得分:1)

将事件处理程序连接到Tabcontrol的选择更改事件。

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e){
//do your filtering here, and set tab control item to the one you want.

答案 1 :(得分:1)

function convertImage($originalImage, $outputImage, $quality){ // jpg, png, gif or bmp? $exploded = explode('.',$originalImage); $ext = $exploded[count($exploded) - 1]; if (preg_match('/jpg|jpeg/i',$ext)){$imageTmp=imagecreatefromjpeg($originalImage);} else if (preg_match('/png/i',$ext)){$imageTmp=imagecreatefrompng($originalImage);} else if (preg_match('/gif/i',$ext)){$imageTmp=imagecreatefromgif($originalImage);} else if (preg_match('/bmp/i',$ext)){$imageTmp=imagecreatefromwbmp($originalImage);} else { return false;} // quality is a value from 0 (worst) to 100 (best) imagejpeg($imageTmp, $outputImage, $quality); imagedestroy($imageTmp); return true; } 是一个错误的事件,您必须使用LostFocus SelectionChanged来阻止标签切换。

下面是一个有效的解决方案(没有MVVM逻辑可能看起来很模糊)。问题是缺少TabControl事件(SelectionChanging更改之前),因此您必须自己记住以前选择的项目。

XAML:

SelectedItem

CS:

<TabControl x:Name="tabControl" SelectionChanged="TabControl_SelectionChanged">
    <TabItem x:Name="dataTab" Header="1" /> <!-- the tab with confirmation -->
    <TabItem Header="2" />
    <TabItem Header="3" />
</TabControl>

最后一行可能需要一些解释:

  1. 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; } 会提升SelectedItem = dataTab事件;
  2. SelectionChanged将被调用;
  3. 在电话TabControl_SelectionChanged()期间,因此没有任何有趣的事情发生;
  4. 返回后,我们设置isPreviousWasDataTab == false