系统在NameScope中无效的强制转换异常

时间:2017-01-17 11:58:57

标签: c# wpf

我在我的应用程序中使用FluidKit。下面的代码在.Net 3.5中正常工作,但在.Net 4.5中引发异常。

private Viewport3D _viewport;

protected override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved)
    {
        base.OnVisualChildrenChanged(visualAdded, visualRemoved);

        if (visualAdded != null)
        {
            UIElement elt = visualAdded as UIElement;
            GeometryModel3D model = CreateMeshModel(elt);
            _modelGroup.Children.Add(model);
            UpdateElementIndexes(elt, true);
            if (IsLoaded)
            {
                ReflowItems();
            }
        }

        if (visualRemoved != null)
        {
            UIElement elt = visualRemoved as UIElement;
            int index = (int) elt.GetValue(ItemIndexProperty);
            GeometryModel3D model = _modelGroup.Children[index] as GeometryModel3D;

            UpdateElementIndexes(elt, false);

            _modelGroup.Children.Remove(model);

            // Update SelectedIndex if needed
            if (SelectedIndex >= 0 && SelectedIndex < VisibleChildrenCount)
            {
                ReflowItems();
            }
            else
            {
                SelectedIndex = Math.Max(0, VisibleChildrenCount - 1);
            }
        }
    }
  private void UpdateElementIndexes(UIElement affectedElement, bool attach)
    {

        try
        {

          // Below line is giving exception :(
           NameScope scope = (NameScope)NameScope.GetNameScope(_viewport);
          ...
          ....

        }

NameScope scope = (NameScope)NameScope.GetNameScope(_viewport);导致异常

  

System.InvalidCastExcpetion:无法转换类型&#39; System.XAML.NameScope&#39;的对象输入&#39; System.Windows.NameScope&#39;

请帮忙

1 个答案:

答案 0 :(得分:2)

这是最令人讨厌的错误之一,基本上它说的是你有2个同名但在不同命名空间中的类,而你正在尝试将一个转换为另一个。

要解决这个问题,只需重写此行:

// change this:
//NameScope scope = (NameScope)NameScope.GetNameScope(_viewport);
// into this :
System.XAML.NameScope scope = (System.XAML.NameScope)NameScope.GetNameScope(_viewport);

编辑:

您始终可以使用var,编译器将执行必要的命名空间导入:

var scope = NameScope.GetNameScope(_viewport);