14

我有一个带有 Treeview 控件的 WPF 应用程序。

当用户单击树上的节点时,页面上的其他 TextBox、ComboBox 等控件将填充适当的值。

然后,用户可以更改这些值并通过单击“保存”按钮保存他或她的更改。

但是,如果用户选择了不同的 Treeview 节点而不保存他或她的更改,我想显示一个警告并有机会取消该选择。

MessageBox:继续并放弃未保存的更改?确定/取消 http://img522.imageshack.us/img522/2897/discardsj3.gif

XAML...

<TreeView Name="TreeViewThings"
    ...
    TreeViewItem.Unselected="TreeViewThings_Unselected"
    TreeViewItem.Selected="TreeViewThings_Selected" >

视觉基本...

Sub TreeViewThings_Unselected(ByVal sender As System.Object, _
                              ByVal e As System.Windows.RoutedEventArgs)
    Dim OldThing As Thing = DirectCast(e.OriginalSource.DataContext, Thing)
    If CancelDueToUnsavedChanges(OldThing) Then
        '这里放取消代码
    万一
结束子

子 TreeViewThings_Selected(ByVal 发件人作为 System.Object,_
                            ByVal e As System.Windows.RoutedEventArgs)
    将 NewThing 调暗为 Thing = DirectCast(e.OriginalSource.DataContext, Thing)
    PopulateControlsFromThing(NewThing)
结束子

如何取消那些取消选择/选择事件?


更新:我问了一个后续问题...
如何正确处理带有 MessageBox 确认的 PreviewMouseDown 事件?

4

9 回答 9

12

更新

意识到我可以将逻辑放在 SelectedItemChanged 中。更清洁的解决方案。

Xaml

<TreeView Name="c_treeView"
          SelectedItemChanged="c_treeView_SelectedItemChanged">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}" />
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>

后面的代码。我有一些类是 TreeView 的 ItemsSource,所以我创建了一个接口 (MyInterface),为所有这些类公开 IsSelected 属性。

private MyInterface m_selectedTreeViewItem = null;
private void c_treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    if (m_selectedTreeViewItem != null)
    {
        if (e.NewValue == m_selectedTreeViewItem)
        {
            // Will only end up here when reversing item
            // Without this line childs can't be selected
            // twice if "No" was pressed in the question..   
            c_treeView.Focus();   
        }
        else
        {
            if (MessageBox.Show("Change TreeViewItem?",
                                "Really change",
                                MessageBoxButton.YesNo,
                                MessageBoxImage.Question) != MessageBoxResult.Yes)
            {
                EventHandler eventHandler = null;
                eventHandler = new EventHandler(delegate
                {
                    c_treeView.LayoutUpdated -= eventHandler;
                    m_selectedTreeViewItem.IsSelected = true;
                });
                // Will be fired after SelectedItemChanged, to early to change back here
                c_treeView.LayoutUpdated += eventHandler;
            }   
            else
            {
                m_selectedTreeViewItem = e.NewValue as MyInterface;
            }        
        }
    }
    else
    {
        m_selectedTreeViewItem = e.NewValue as MyInterface;
    }
}

我还没有发现在按“否”后它不会恢复到上一个​​项目的任何情况。

于 2010-10-27T00:22:42.237 回答
4

我必须解决同样的问题,但在我的应用程序的多个树视图中。我派生了 TreeView 并添加了事件处理程序,部分使用 Meleak 的解决方案,部分使用来自该论坛的扩展方法:http ://forums.silverlight.net/t/65277.aspx/1/10

我想我会和你分享我的解决方案,所以这是我处理“取消节点更改”的完整可重用 TreeView:

public class MyTreeView : TreeView
{
    public static RoutedEvent PreviewSelectedItemChangedEvent;
    public static RoutedEvent SelectionCancelledEvent;

    static MyTreeView()
    {
        PreviewSelectedItemChangedEvent = EventManager.RegisterRoutedEvent("PreviewSelectedItemChanged", RoutingStrategy.Bubble,
                                                                           typeof(RoutedPropertyChangedEventHandler<object>), typeof(MyTreeView));

        SelectionCancelledEvent = EventManager.RegisterRoutedEvent("SelectionCancelled", RoutingStrategy.Bubble,
                                                                   typeof(RoutedEventHandler), typeof(MyTreeView));
    }

    public event RoutedPropertyChangedEventHandler<object> PreviewSelectedItemChanged
    {
        add { AddHandler(PreviewSelectedItemChangedEvent, value); }
        remove { RemoveHandler(PreviewSelectedItemChangedEvent, value); }
    }

    public event RoutedEventHandler SelectionCancelled
    {
        add { AddHandler(SelectionCancelledEvent, value); }
        remove { RemoveHandler(SelectionCancelledEvent, value); }
    }


    private object selectedItem = null;
    protected override void OnSelectedItemChanged(RoutedPropertyChangedEventArgs<object> e)
    {
        if (e.NewValue == selectedItem)
        {
            this.Focus();

            var args = new RoutedEventArgs(SelectionCancelledEvent);
            RaiseEvent(args);
        }
        else
        {
            var args = new RoutedPropertyChangedEventArgs<object>(e.OldValue, e.NewValue, PreviewSelectedItemChangedEvent);
            RaiseEvent(args);

            if (args.Handled)
            {
                EventHandler eventHandler = null;
                eventHandler = delegate
                {
                    this.LayoutUpdated -= eventHandler;

                    var treeViewItem = this.ContainerFromItem(selectedItem);
                    if (treeViewItem != null)
                        treeViewItem.IsSelected = true;
                };

                this.LayoutUpdated += eventHandler;
            }
            else
            {
                selectedItem = this.SelectedItem;
                base.OnSelectedItemChanged(e);
            }
        }
    }
}

public static class TreeViewExtensions
{
    public static TreeViewItem ContainerFromItem(this TreeView treeView, object item)
    {
        if (item == null) return null;

        var containerThatMightContainItem = (TreeViewItem)treeView.ItemContainerGenerator.ContainerFromItem(item);

        return containerThatMightContainItem ?? ContainerFromItem(treeView.ItemContainerGenerator, treeView.Items, item);
    }

    private static TreeViewItem ContainerFromItem(ItemContainerGenerator parentItemContainerGenerator, ItemCollection itemCollection, object item)
    {
        foreach (var child in itemCollection)
        {
            var parentContainer = (TreeViewItem)parentItemContainerGenerator.ContainerFromItem(child);
            var containerThatMightContainItem = (TreeViewItem)parentContainer.ItemContainerGenerator.ContainerFromItem(item);

            if (containerThatMightContainItem != null)
                return containerThatMightContainItem;

            var recursionResult = ContainerFromItem(parentContainer.ItemContainerGenerator, parentContainer.Items, item);
            if (recursionResult != null)
                return recursionResult;
        }
        return null;
    }
}

这是一个使用示例(包含 MyTreeView 的窗口的代码隐藏):

    private void theTreeView_PreviewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        if (e.OldValue != null)
            e.Handled = true;
    }

    private void theTreeView_SelectionCancelled(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Cancelled");
    }

在树视图中选择第一个节点后,所有其他节点更改都被取消并显示一个消息框。

于 2012-03-22T07:11:43.113 回答
3

您实际上不能将逻辑放入 OnSelectedItemChanged 方法中,如果存在逻辑,则 Selected Item 实际上已经更改。

正如另一张海报所建议的,PreviewMouseDown 处理程序是实现逻辑的更好位置,但是,仍然需要完成大量的工作。

下面是我的 2 美分:

首先是我实现的 TreeView:

public class MyTreeView : TreeView
{
    static MyTreeView( )
    {
        DefaultStyleKeyProperty.OverrideMetadata(
            typeof(MyTreeView),
            new FrameworkPropertyMetadata(typeof(TreeView)));
    }

    // Register a routed event, note this event uses RoutingStrategy.Tunnel. per msdn docs
    // all "Preview" events should use tunneling.
    // http://msdn.microsoft.com/en-us/library/system.windows.routedevent.routingstrategy.aspx
    public static RoutedEvent PreviewSelectedItemChangedEvent = EventManager.RegisterRoutedEvent(
        "PreviewSelectedItemChanged",
        RoutingStrategy.Tunnel,
        typeof(CancelEventHandler),
        typeof(MyTreeView));

    // give CLR access to routed event
    public event CancelEventHandler PreviewSelectedItemChanged
    {
        add
        {
            AddHandler(PreviewSelectedItemChangedEvent, value);
        }
        remove
        {
            RemoveHandler(PreviewSelectedItemChangedEvent, value);
        }
    }

    // override PreviewMouseDown
    protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
    {
        // determine which item is going to be selected based on the current mouse position
        object itemToBeSelected = this.GetObjectAtPoint<TreeViewItem>(e.GetPosition(this));

        // selection doesn't change if the target point is null (beyond the end of the list)
        // or if the item to be selected is already selected.
        if (itemToBeSelected != null && itemToBeSelected != SelectedItem)
        {
            bool shouldCancel;

            // call our new event
            OnPreviewSelectedItemChanged(out shouldCancel);
            if (shouldCancel)
            {
                // if we are canceling the selection, mark this event has handled and don't
                // propogate the event.
                e.Handled = true;
                return;
            }
        }

        // otherwise we want to continue normally
        base.OnPreviewMouseDown(e);
    }

    protected virtual void OnPreviewSelectedItemChanged(out bool shouldCancel)
    {
        CancelEventArgs e = new CancelEventArgs( );
        if (PreviewSelectedItemChangedEvent != null)
        {
            // Raise our event with our custom CancelRoutedEventArgs
            RaiseEvent(new CancelRoutedEventArgs(PreviewSelectedItemChangedEvent, e));
        }
        shouldCancel = e.Cancel;
    }
}

一些扩展方法来支持 TreeView 在鼠标下查找对象。

public static class ItemContainerExtensions
{
    // get the object that exists in the container at the specified point.
    public static object GetObjectAtPoint<ItemContainer>(this ItemsControl control, Point p)
        where ItemContainer : DependencyObject
    {
        // ItemContainer - can be ListViewItem, or TreeViewItem and so on(depends on control)
        ItemContainer obj = GetContainerAtPoint<ItemContainer>(control, p);
        if (obj == null)
            return null;

        // it is worth noting that the passed _control_ may not be the direct parent of the
        // container that exists at this point. This can be the case in a TreeView, where the
        // parent of a TreeViewItem may be either the TreeView or a intermediate TreeViewItem
        ItemsControl parentGenerator = obj.GetParentItemsControl( );

        // hopefully this isn't possible?
        if (parentGenerator == null)
            return null;

        return parentGenerator.ItemContainerGenerator.ItemFromContainer(obj);
    }

    // use the VisualTreeHelper to find the container at the specified point.
    public static ItemContainer GetContainerAtPoint<ItemContainer>(this ItemsControl control, Point p)
        where ItemContainer : DependencyObject
    {
        HitTestResult result = VisualTreeHelper.HitTest(control, p);
        DependencyObject obj = result.VisualHit;

        while (VisualTreeHelper.GetParent(obj) != null && !(obj is ItemContainer))
        {
            obj = VisualTreeHelper.GetParent(obj);
        }

        // Will return null if not found
        return obj as ItemContainer;
    }

    // walk up the visual tree looking for the nearest ItemsControl parent of the specified
    // depObject, returns null if one isn't found.
    public static ItemsControl GetParentItemsControl(this DependencyObject depObject)
    {
        DependencyObject obj = VisualTreeHelper.GetParent(depObject);
        while (VisualTreeHelper.GetParent(obj) != null && !(obj is ItemsControl))
        {
            obj = VisualTreeHelper.GetParent(obj);
        }

        // will return null if not found
        return obj as ItemsControl;
    }
}

最后但并非最不重要的是利用 RoutedEvent 子系统的自定义 EventArgs。

public class CancelRoutedEventArgs : RoutedEventArgs
{
    private readonly CancelEventArgs _CancelArgs;

    public CancelRoutedEventArgs(RoutedEvent @event, CancelEventArgs cancelArgs)
        : base(@event)
    {
        _CancelArgs = cancelArgs;
    }

    // override the InvokeEventHandler because we are going to pass it CancelEventArgs
    // not the normal RoutedEventArgs
    protected override void InvokeEventHandler(Delegate genericHandler, object genericTarget)
    {
        CancelEventHandler handler = (CancelEventHandler)genericHandler;
        handler(genericTarget, _CancelArgs);
    }

    // the result
    public bool Cancel
    {
        get
        {
            return _CancelArgs.Cancel;
        }
    }
}
于 2013-03-19T15:21:58.300 回答
2

CAMS_ARIES:

XAML:

代码 :

  private bool ManejarSeleccionNodoArbol(Object origen)
    {
        return true;  // with true, the selected nodo don't change
        return false // with false, the selected nodo change
    }


    private void Arbol_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {            
        if (e.Source is TreeViewItem)
        {
            e.Handled = ManejarSeleccionNodoArbol(e.Source);
        }
    }

    private void Arbol_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Source is TreeViewItem)
        {
           e.Handled=ManejarSeleccionNodoArbol(e.Source);
        }
    }         
于 2009-08-14T02:03:20.443 回答
2

您不能像取消事件那样取消事件,例如 Closing 事件。但是,如果您缓存最后选择的值,则可以撤消它。秘诀是您必须在不重新触发 SelectionChanged 事件的情况下更改选择。这是一个例子:

    private object _LastSelection = null;
    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (IsUpdated)
        {
            MessageBoxResult result = MessageBox.Show("The current record has been modified. Are you sure you want to navigate away? Click Cancel to continue editing. If you click OK all changes will be lost.", "Warning", MessageBoxButton.OKCancel, MessageBoxImage.Hand);
            switch (result)
            {
                case MessageBoxResult.Cancel:
                    e.Handled = true;
                    // disable event so this doesn't go into an infinite loop when the selection is changed to the cached value
                    PersonListView.SelectionChanged -= new SelectionChangedEventHandler(OnSelectionChanged);
                    PersonListView.SelectedItem = _LastSelection;
                    PersonListView.SelectionChanged += new SelectionChangedEventHandler(OnSelectionChanged);
                    return;
                case MessageBoxResult.OK:
                    // revert the object to the original state
                    LocalDataContext.Persons.GetOriginalEntityState(_LastSelection).CopyTo(_LastSelection);
                    IsUpdated = false;
                    Refresh();
                    break;
                default:
                    throw new ApplicationException("Invalid response.");
            }
        }

        // cache the selected item for undo
        _LastSelection = PersonListView.SelectedItem;
    }
于 2009-02-12T18:49:23.430 回答
2

与其选择 Selected/Unselected,更好的方法可能是挂钩 PreviewMouseDown。处理 Selected 和 Unselected 事件的前提是当您收到通知时该事件已经发生。没有什么可以取消的,因为它已经发生了。

另一方面,预览事件是可取消的。这不是您想要的确切事件,但它确实为您提供了防止用户选择其他节点的机会。

于 2009-02-12T17:34:04.560 回答
1

您可以创建派生自 TreeView 的自定义控件,然后重写 OnSelectedItemChanged 方法。

在调用基础之前,您可以首先使用 CancelEventArgs 参数触发自定义事件。如果 parameter.Cancel 变为 true,则不要调用 base,而是选择旧项目(注意 OnSelectedItemChanged 将再次被调用)。

不是最好的解决方案,但至少这将逻辑保留在树控件内,并且选择更改事件触发的次数不会超过需要的次数。此外,您无需关心用户是否单击了树、使用了键盘或者选择是否以编程方式更改。

于 2011-04-11T10:58:03.063 回答
1

由于该SelectedItemChanged事件是在SelectedItem已经更改后触发的,因此此时您无法真正取消该事件。

您可以做的是监听鼠标点击并在SelectedItem更改之前取消它们。

于 2009-02-12T17:33:37.917 回答
0

我为 1 个树视图和一次显示 1 个文档解决了这个问题。此解决方案基于可附加到普通树视图的可附加行为:

<TreeView Grid.Column="0"
       ItemsSource="{Binding TreeViewItems}"
       behav:TreeViewSelectionChangedBehavior.ChangedCommand="{Binding SelectItemChangedCommand}"
       >
     <TreeView.ItemTemplate>
         <HierarchicalDataTemplate ItemsSource="{Binding Children}">
             <StackPanel Orientation="Horizontal">
                 <TextBlock Text="{Binding Name}"
                         ToolTipService.ShowOnDisabled="True"
                         VerticalAlignment="Center" Margin="3" />
             </StackPanel>
         </HierarchicalDataTemplate>
     </TreeView.ItemTemplate>
     <TreeView.ItemContainerStyle>
         <Style TargetType="{x:Type TreeViewItem}">
             <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
             <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
         </Style>
     </TreeView.ItemContainerStyle>
</TreeView>

行为的代码是这样的:

/// <summary>
/// Source:
/// http://stackoverflow.com/questions/1034374/drag-and-drop-in-mvvm-with-scatterview
/// http://social.msdn.microsoft.com/Forums/de-DE/wpf/thread/21bed380-c485-44fb-8741-f9245524d0ae
/// 
/// Attached behaviour to implement the SelectionChanged command/event via delegate command binding or routed commands.
/// </summary>
public static class TreeViewSelectionChangedBehavior
{
#region fields
/// <summary>
/// Field of attached ICommand property
/// </summary>
private static readonly DependencyProperty ChangedCommandProperty = DependencyProperty.RegisterAttached(
  "ChangedCommand",
  typeof(ICommand),
  typeof(TreeViewSelectionChangedBehavior),
  new PropertyMetadata(null, OnSelectionChangedCommandChange));

/// <summary>
/// Implement backing store for UndoSelection dependency proeprty to indicate whether selection should be
/// cancelled via MessageBox query or not.
/// </summary>
public static readonly DependencyProperty UndoSelectionProperty =
  DependencyProperty.RegisterAttached("UndoSelection",
  typeof(bool),
  typeof(TreeViewSelectionChangedBehavior),
  new PropertyMetadata(false, OnUndoSelectionChanged));
#endregion fields

#region methods
#region ICommand changed methods
/// <summary>
/// Setter method of the attached ChangedCommand <seealso cref="ICommand"/> property
/// </summary>
/// <param name="source"></param>
/// <param name="value"></param>
public static void SetChangedCommand(DependencyObject source, ICommand value)
{
  source.SetValue(ChangedCommandProperty, value);
}

/// <summary>
/// Getter method of the attached ChangedCommand <seealso cref="ICommand"/> property
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static ICommand GetChangedCommand(DependencyObject source)
{
  return (ICommand)source.GetValue(ChangedCommandProperty);
}
#endregion ICommand changed methods

#region UndoSelection methods
public static bool GetUndoSelection(DependencyObject obj)
{
  return (bool)obj.GetValue(UndoSelectionProperty);
}

public static void SetUndoSelection(DependencyObject obj, bool value)
{
  obj.SetValue(UndoSelectionProperty, value);
}
#endregion UndoSelection methods

/// <summary>
/// This method is hooked in the definition of the <seealso cref="ChangedCommandProperty"/>.
/// It is called whenever the attached property changes - in our case the event of binding
/// and unbinding the property to a sink is what we are looking for.
/// </summary>
/// <param name="d"></param>
/// <param name="e"></param>
private static void OnSelectionChangedCommandChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
  TreeView uiElement = d as TreeView;  // Remove the handler if it exist to avoid memory leaks

  if (uiElement != null)
  {
      uiElement.SelectedItemChanged -= Selection_Changed;

      var command = e.NewValue as ICommand;
      if (command != null)
      {
          // the property is attached so we attach the Drop event handler
          uiElement.SelectedItemChanged += Selection_Changed;
      }
  }
}

/// <summary>
/// This method is called when the selection changed event occurs. The sender should be the control
/// on which this behaviour is attached - so we convert the sender into a <seealso cref="UIElement"/>
/// and receive the Command through the <seealso cref="GetChangedCommand"/> getter listed above.
/// 
/// The <paramref name="e"/> parameter contains the standard EventArgs data,
/// which is unpacked and reales upon the bound command.
/// 
/// This implementation supports binding of delegate commands and routed commands.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void Selection_Changed(object sender, RoutedPropertyChangedEventArgs<object> e)
{
  var uiElement = sender as TreeView;

  // Sanity check just in case this was somehow send by something else
  if (uiElement == null)
      return;

  ICommand changedCommand = TreeViewSelectionChangedBehavior.GetChangedCommand(uiElement);

  // There may not be a command bound to this after all
  if (changedCommand == null)
      return;

  // Check whether this attached behaviour is bound to a RoutedCommand
  if (changedCommand is RoutedCommand)
  {
      // Execute the routed command
      (changedCommand as RoutedCommand).Execute(e.NewValue, uiElement);
  }
  else
  {
      // Execute the Command as bound delegate
      changedCommand.Execute(e.NewValue);
  }
}

/// <summary>
/// Executes when the bound boolean property indicates that a user should be asked
/// about changing a treeviewitem selection instead of just performing it.
/// </summary>
/// <param name="d"></param>
/// <param name="e"></param>
private static void OnUndoSelectionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
  TreeView uiElement = d as TreeView;  // Remove the handler if it exist to avoid memory leaks

  if (uiElement != null)
  {
      uiElement.PreviewMouseDown -= uiElement_PreviewMouseDown;

      var command = (bool)e.NewValue;
      if (command == true)
      {
          // the property is attached so we attach the Drop event handler
          uiElement.PreviewMouseDown += uiElement_PreviewMouseDown;
      }
  }
}

/// <summary>
/// Based on the solution proposed here:
/// Source: http://stackoverflow.com/questions/20244916/wpf-treeview-selection-change
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void uiElement_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
  // first did the user click on a tree node?
  var source = e.OriginalSource as DependencyObject;
  while (source != null && !(source is TreeViewItem))
      source = VisualTreeHelper.GetParent(source);

  var itemSource = source as TreeViewItem;
  if (itemSource == null)
      return;

  var treeView = sender as TreeView;
  if (treeView == null)
      return;

  bool undoSelection = TreeViewSelectionChangedBehavior.GetUndoSelection(treeView);
  if (undoSelection == false)
      return;

  // Cancel the attempt to select an item.
  var result = MessageBox.Show("The current document has unsaved data. Do you want to continue without saving data?", "Are you really sure?",
                               MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);

  if (result == MessageBoxResult.No)
  {
      // Cancel the attempt to select a differnet item.
      e.Handled = true;
  }
  else
  {
      // Lets disable this for a moment, otherwise, we'll get into an event "recursion"
      treeView.PreviewMouseDown -= uiElement_PreviewMouseDown;

      // Select the new item - make sure a SelectedItemChanged event is fired in any case
      // Even if this means that we have to deselect/select the one and the same item
      if (itemSource.IsSelected == true )
          itemSource.IsSelected = false;

      itemSource.IsSelected = true;

      // Lets enable this to get back to business for next selection
      treeView.PreviewMouseDown += uiElement_PreviewMouseDown;
  }
}
#endregion methods
}

在此示例中,我显示了一个阻止消息框,以便在 PreviewMouseDown 事件发生时阻止它。然后处理该事件以表示选择已取消,或者不处理该事件以让树视图本身通过选择即将被选择的项目来处理事件。

如果用户决定继续,该行为然后调用视图模型中的绑定命令(PreviewMouseDown 事件不由附加行为处理,并且调用绑定命令。

我猜消息框显示可以通过其他方式完成,但我认为它必须在这里阻止事件发生,因为否则无法取消它(?)。因此,我可能想到的关于此代码的唯一改进是绑定一些字符串以使显示的消息可配置。

我写了一篇包含可下载示例的文章,因为这是一个难以解释的领域(必须对缺失的部分做出许多假设,并且可能并不总是被所有读者共享)

这是一篇包含我的结果的文章:http: //www.codeproject.com/Articles/995629/Cancelable-TreeView-Navigation-for-Documents-in-WP

请对此解决方案发表评论,如果您发现有改进的余地,请告诉我。

于 2015-06-11T00:43:59.393 回答