我有一个带有一些TabControl的应用程序,并且在特定的选项卡中可以启动长计算。我希望用户确认离开选项卡并中止计算。 到目前为止,我创建了一个Behavior并将其附加到tabcontrol。 (最后的代码)。 我的问题:假设我想要退出标签#3。 我选择标签#2 - >确认对话框弹出,我选择否(CanNavigateFromMe()== false),然后返回选项卡#3。 再次,我选择选项卡#2并获得相同的行为。 我想第三次选择它 - 现在,单击标题不会触发CurrentChanging事件!
行为代码:
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += new System.Windows.RoutedEventHandler(AssociatedObject_Loaded);
}
void AssociatedObject_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
// required in order to get CurrentItemChanging
AssociatedObject.IsSynchronizedWithCurrentItem = true;
AssociatedObject.Items.CurrentChanging += new CurrentChangingEventHandler(Items_CurrentChanging);
}
void Items_CurrentChanging(object sender, CurrentChangingEventArgs e)
{
var item = ((ICollectionView)sender).CurrentItem;
var view = item as FrameworkElement;
if (view == null)
{
return;
}
IAllowNavigation allowNavigation = view.DataContext as IAllowNavigation;
if ((allowNavigation != null) &&
(allowNavigation.CanNavigateFromMe() == false))
{
e.Cancel = true;
AssociatedObject.SelectedItem = view;
}
}
答案 0 :(得分:0)
在朋友的帮助下,我发现我需要: 1.如果取消选择,则在集合上调用Refresh()。 2.如果我决定允许选择,请确保进行原始选择(这涉及用户输入并花费时间,同时其他选项卡中的内容可以更改所选项目)
void Items_CurrentChanging(object sender, CurrentChangingEventArgs e)
{
var newItem = AssociatedObject.SelectedItem;
var item = ((ICollectionView)sender).CurrentItem;
var view = item as FrameworkElement;
if (view == null)
{
return;
}
IAllowNavigation allowNavigation = view.DataContext as IAllowNavigation;
if ((allowNavigation != null) &&
(allowNavigation.CanNavigateFromMe() == false))
{
e.Cancel = true;
AssociatedObject.SelectedItem = view;
}
else
{
AssociatedObject.SelectedItem = newItem;
}
((ICollectionView)sender).Refresh();
}