“因为正在进行树遍历,所以此时无法修改该节点的逻辑子级”是什么意思?

20
在后台工作线程的completed方法中设置对象的DataContext。出现错误,提示:“Cannot modify the logical children for this node at this time because a tree walk is in progress pointing to the Chart1.DataContext=allDates line.”。什么是“tree walk is in progress”?我也尝试使用Dispatcher操作进行设置,但仍然出现相同的错误……有什么建议吗?在这个错误消息上谷歌无果。这造成错误的代码是Microsoft的Charting工具包内部的,我想知道是否发现了控件中的错误。不使用Dispatcher:
 void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        ArticlesPerTimePeriodResult result = (ArticlesPerTimePeriodResult)e.Result;
        lvArticles.ItemsSource = result.DatesOfArticles;


        Chart1.DataContext = result.AllDates;
    }

使用 Dispatcher:

 void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        ArticlesPerTimePeriodResult result = (ArticlesPerTimePeriodResult)e.Result;
        lvArticles.ItemsSource = result.DatesOfArticles;

        Dispatcher.BeginInvoke((Action<List<KeyValuePair<DateTime,int>>>)(delegate(List<KeyValuePair<DateTime,int>> allDates)
        {
            Chart1.DataContext = allDates;
        }), result.AllDates);

        //Chart1.DataContext = result.AllDates;
    }

错误:

System.Reflection.TargetInvocationException was unhandled
  Message="Exception has been thrown by the target of an invocation."
  Source="mscorlib"
  StackTrace:
       at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
       at System.Delegate.DynamicInvokeImpl(Object[] args)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
       at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.DispatcherOperation.InvokeImpl()
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.ProcessQueue()
       at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
       at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.TranslateAndDispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Application.RunInternal(Window window)
       at NewsCluesWpf.App.Main() in C:\SoftwareInstall\VSProjects\NewsClues\NewsCluesWpf\obj\Debug\App.g.cs:line 0
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.InvalidOperationException
       Message="Cannot modify the logical children for this node at this time because a tree walk is in progress."
       Source="PresentationFramework"
       StackTrace:
            at System.Windows.FrameworkElement.AddLogicalChild(Object child)
            at System.Windows.Controls.UIElementCollection.InsertInternal(Int32 index, UIElement element)
            at System.Windows.Controls.DataVisualization.ObservableCollectionListAdapter`1.<>c__DisplayClass1.<OnCollectionChanged>b__0(T item, Int32 index)
            at System.Windows.Controls.DataVisualization.EnumerableFunctions.ForEachWithIndex[T](IEnumerable`1 that, Action`2 action)
            at System.Windows.Controls.DataVisualization.ObservableCollectionListAdapter`1.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
            at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
            at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedAction action, Object item, Int32 index)
            at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item)
            at System.Windows.Controls.DataVisualization.ReadOnlyObservableCollection`1.InsertItem(Int32 index, T item)
            at System.Collections.ObjectModel.Collection`1.Insert(Int32 index, T item)
            at System.Windows.Controls.DataVisualization.AggregatedObservableCollection`1.<>c__DisplayClass14.<>c__DisplayClass16.<ChildCollectionCollectionChanged>b__f(ReadOnlyObservableCollection`1 that)
            at System.Windows.Controls.DataVisualization.ReadOnlyObservableCollection`1.Mutate(Action`1 action)
            at System.Windows.Controls.DataVisualization.AggregatedObservableCollection`1.<>c__DisplayClass14.<ChildCollectionCollectionChanged>b__e(T item, Int32 index)
            at System.Windows.Controls.DataVisualization.EnumerableFunctions.ForEachWithIndex[T](IEnumerable`1 that, Action`2 action)
            at System.Windows.Controls.DataVisualization.AggregatedObservableCollection`1.ChildCollectionCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
            at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
            at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedAction action, Object item, Int32 index)
            at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item)
            at System.Collections.ObjectModel.Collection`1.Add(T item)
            at System.Windows.Controls.DataVisualization.Charting.Chart.AddAxisToChartArea(Axis axis)
            at System.Windows.Controls.DataVisualization.Charting.Chart.ActualAxesCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
            at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
            at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
            at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedAction action, Object item, Int32 index)
            at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item)
            at System.Windows.Controls.DataVisualization.UniqueObservableCollection`1.InsertItem(Int32 index, T item)
            at System.Collections.ObjectModel.Collection`1.Add(T item)
            at System.Windows.Controls.DataVisualization.Charting.DataPointSeriesWithAxes.GetAxes(DataPoint firstDataPoint, Func`2 independentAxisPredicate, Func`1 independentAxisFactory, Func`2 dependentAxisPredicate, Func`1 dependentAxisFactory)
            at System.Windows.Controls.DataVisualization.Charting.AreaSeries.GetAxes(DataPoint firstDataPoint)
            at System.Windows.Controls.DataVisualization.Charting.DataPointSeriesWithAxes.GetAxes()
            at System.Windows.Controls.DataVisualization.Charting.DataPointSeriesWithAxes.OnDataPointsChanged(IList`1 newDataPoints, IList`1 oldDataPoints)
            at System.Windows.Controls.DataVisualization.Charting.DataPointSingleSeriesWithAxes.OnDataPointsChanged(IList`1 newDataPoints, IList`1 oldDataPoints)
            at System.Windows.Controls.DataVisualization.Charting.LineAreaBaseSeries`1.OnDataPointsChanged(IList`1 newDataPoints, IList`1 oldDataPoints)
            at System.Windows.Controls.DataVisualization.Charting.DataPointSeries.LoadDataPoints(IEnumerable newItems, IEnumerable oldItems)
            at System.Windows.Controls.DataVisualization.Charting.DataPointSeries.Refresh()
            at System.Windows.Controls.DataVisualization.Charting.DataPointSeries.OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
            at System.Windows.Controls.DataVisualization.Charting.DataPointSeries.OnItemsSourceChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
            at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
            at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
            at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
            at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType)
            at System.Windows.DependencyObject.InvalidateProperty(DependencyProperty dp)
            at System.Windows.Data.BindingExpression.Invalidate(Boolean isASubPropertyChange)
            at System.Windows.Data.BindingExpression.TransferValue(Object newValue, Boolean isASubPropertyChange)
            at System.Windows.Data.BindingExpression.Activate(Object item)
            at System.Windows.Data.BindingExpression.HandlePropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args)
            at System.Windows.Data.BindingExpression.OnPropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args)
            at System.Windows.DependentList.InvalidateDependents(DependencyObject source, DependencyPropertyChangedEventArgs sourceArgs)
            at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
            at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType)
            at System.Windows.TreeWalkHelper.OnInheritablePropertyChanged(DependencyObject d, InheritablePropertyChangeInfo info)
            at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d)
            at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren)
            at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren)
            at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d)
            at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d)
            at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren)
            at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren)
            at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d)
            at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d)
            at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren)
            at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren)
            at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d)
            at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d)
            at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren)
            at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren)
            at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d)
            at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d)
            at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren)
            at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d)
            at System.Windows.DescendentsWalker`1.StartWalk(DependencyObject startNode, Boolean skipStartNode)
            at System.Windows.TreeWalkHelper.InvalidateOnInheritablePropertyChange(FrameworkElement fe, FrameworkContentElement fce, InheritablePropertyChangeInfo info, Boolean skipStartNode)
            at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
            at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
            at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType)
            at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, OperationType operationType, Boolean isInternal)
            at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
            at System.Windows.FrameworkElement.set_DataContext(Object value)
            at NewsCluesWpf.ArticlesPerDay.<bg_RunWorkerCompleted>b__1(List`1 allDates) in C:\SoftwareInstall\VSProjects\NewsClues\NewsCluesWpf\ArticlesPerDay.xaml.cs:line 72
       InnerException: 

我相信后台工作程序调用的已完成部分是在调用线程上完成的,而不是后台线程上完成的,因此,除非调用线程本身不是UI线程,否则您不需要一个调度程序。 - PeterAllenWebb
9个回答

10

已解决!

问题:我希望在GUI中每次更改数据时更新我的图表。

 myChart.DataContext = MTFdata;

当我执行此操作时,出现错误:Cannot modify the logical children for this node at this time because a tree walk is in progress。

我的解决方法:

不要使用以下方式:

 <chartingToolkit:LineSeries   DependentValuePath="Key" 
                                                    IndependentValuePath="Value" 
                                                    ItemsSource="{Binding}"
                                                    IsSelectionEnabled="False"
                                                                             >

使用这个:

 <chartingToolkit:LineSeries   DependentValuePath="Key" 
                                                    IndependentValuePath="Value" 
                                                    ItemsSource="{Binding}"
                                                    DataContext="{Binding}"
                                                    IsSelectionEnabled="False"
                                                                             >

请同时使用ItemsSource="{Binding}"DataContext="{Binding}"

希望这可以帮到您!


8

在进一步尝试后,我认为这是Silverlight图表工具包中的一个bug。

以下代码会导致可重现的崩溃。

int runCount = 0;
        private void bindChart(string searchString)
        {
           List<KeyValuePair<DateTime, int>> dataEmpty = new List<KeyValuePair<DateTime, int>>();

            List<KeyValuePair<DateTime, int>> dataFilled = new List<KeyValuePair<DateTime, int>>();
            dataFilled.Add(new KeyValuePair<DateTime, int>(DateTime.Today, 1));
            if (runCount == 0)
            {
                Chart1.DataContext= dataEmpty;
            }
            else
            {
                Chart1.DataContext = dataFilled;
            }
            runCount++;

        }

XAML:

<charting:Chart Grid.Row="0"
    Title="Title"
    LegendTitle="Legend" Name="Chart1" Grid.RowSpan="2">
            <charting:AreaSeries ItemsSource="{Binding}"

                                       DependentValuePath="Value"

                                       IndependentValuePath="Key"

                                       Background="Red" />


        </charting:Chart>

第二次调用bindChart将会失败。


5
我在CodePlex上提交了一个缺陷报告。结果发现这是图表框架中的一个错误。请参见http://silverlight.codeplex.com/WorkItem/View.aspx?WorkItemId=3258有一个解决方法。将图表的DataPointSeries项源设置为数据上下文而不是:
(Chart1.Series [0] as DataPointSeries).ItemsSource = dataEmpty;
- Sean Turner
这个修复方法也适用于在VS2013中使用WPF。个人而言,我遵循MVVM模式,因此我创建了一个带有依赖属性的行为,并将其绑定到DataContext上。这个DP的更改处理程序然后将其分配给系列,使用"((d as MyChartBehavior).AssociatedObject as DataPointSeries).ItemsSource = e.NewValue as IEnumerable;" - Mark Feldman

2

你好,

我刚遇到了这个错误,并且已经解决了。

当设置数据上下文时,也会出现此错误。

我发现在列表中有一个选择更改订阅,而该列表正在设置其数据上下文。 在这个选择更改中,我正在更改另一个具有通知支持的属性,该属性具有可视元素绑定。

通过使用调度程序来设置属性来解决问题。

因此,请尝试查找更改的订阅...


0

不需要重置DataContext,可以通过可观察集合进行重用...

    int runCount = 0;

    private void bindChart()
    {
        ObservableCollection<KeyValuePair<DateTime, int>> data = new ObservableCollection<KeyValuePair<DateTime, int>>();

        if (runCount == 0)
        {
            this.DataContext = dataEmpty;
        }
        else
        {
            var de = this.DataContext as ObservableCollection<KeyValuePair<DateTime, int>>;
            de.Clear();
            for (var i = 0; i < (new Random(DateTime.Now.Second)).Next(100); i++)
            {
                de.Add(new KeyValuePair<DateTime, int>(DateTime.Today.AddDays(i), i));
            }
        }

        runCount++;
    } 

0
我最近在使用WPF图表工具包时遇到了这个问题。大家都说不要绑定到DataContext,而是直接绑定到ItemsSource,但我已经绑定到了ItemsSource,仍然出现了错误。在我的情况下,我是绑定到ListBox或TreeView的SelectedItem。唯一能让我解决问题的方法是在SelectedItemChanged()事件触发时手动绑定到ItemsSource。
private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    if (TreeView.SelectedItem != null)
        LineSeries.ItemsSource = (TreeView.SelectedItem as MyObject).Items;
}

0

这是我的相关研究。

在 WaybackMachine 上的该链接镜像

这是一个 WPF 异常,由 FrameworkElement 和 FrameworkContentElement 中的 Add/RemoveLogicalChild 方法在树遍历过程中抛出。关于其无聊的细节可以参考博客文章,但重要的是你不能够做比检测它更多的事情,只能在它发生的地方捕获它。这个异常应该相对较少出现。


0

当父控件(AvalonDock)触发子用户控件重新加载时,我遇到了这个问题:用户控件会触发其“Loaded”事件,导致我的应用程序崩溃。

我从用户控件中删除了“Loaded”事件处理程序,并改用“Initialized”事件。虽然我不完全确定原因,但这解决了我的问题。


0

显然,在使用集合时正在进行某些操作,这会改变它。这是一个大忌。

没有进一步分析代码,我就只能说这么多了。


-1

我有同样的问题。虽然我没有使用任何后台线程,但我只是有一个滑块,在滑块的ValueChanged事件上,我在重新计算和重置DataContext。

例如,一个燃尽图。随着初始值的改变,图形会自动更新(基本上是折线系列的Y轴)。

在Silverlight 3的测试版中,更改数据上下文是有效的。但在正式版中不起作用。上述评论提到设置(Chart1.Series [0] as DataPointSeries)。ItemsSource对我起作用。


请问给这篇将近四年前的帖子投反对票的人可以解释一下为什么吗? - Chaitanya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接