如何在View Model中进行命中测试?

时间:2014-08-24 05:50:31

标签: wpf xaml mvvm hittest

我似乎无法通过Google找到这个。在使用MVVM的WPF中,我有一个用于视图的InkCanvas。在这个InkCanvas下,还有几个画布提供不同的文本信息。

将InkCanvas与PreviewMouseDown绑定到视图模型为viewBodel提供了MouseButtonEventArgs,我相信我可以从中获取鼠标位置(相对于什么?)

但是,当viewmodel没有对视图的引用时,从较低的画布中获取文本元素的最佳方法是什么?如何在viewmodel中进行命中测试???

视图模型:

private RelayCommand inkCanvas_PreviewMouseDown;
    public RelayCommand InkCanvas_PreviewMouseDown
    {
        get
        {

            if (inkCanvas_PreviewMouseDown == null)
            {                   
              inkCanvas_PreviewMouseDown = new RelayCommand( (p) => { this.method(p); 
                });
            }
            return inkCanvas_PreviewMouseDown;
        }
    }

    private void method(Object e)
    {
        MouseButtonEventArgs args = e as MouseButtonEventArgs;
        Point pt = args.GetPosition(null);

      ??? How to find the elements  below the point on the other layers?
      HitTestResult hit = VisualTreeHelper.HitTest(args.Source, pt);  <--This is wrong.
    }

XAML

  <ink:CustomInkCanvas x:Name="inkcanvas" Panel.ZIndex="4" 
                        Width="{x:Static h:Constants.widthCanvas}"
                        Height ="{x:Static h:Constants.heightCanvas}"          
                        Background="Transparent" 
                        DefaultDrawingAttributes="{Binding DDA}" 
                        EditingMode="{Binding EditingMode}" 
                        Strokes="{Binding Strokes}"
                        h:MouseBehaviour.PreviewMouseDownCommand="{Binding InkCanvas_PreviewMouseDown}"                                   
                        >
 </ink:CustomInkCanvas>

1 个答案:

答案 0 :(得分:0)

由于我还没有接受者,我将解释我最终做的事情,希望能帮助其他人。

据我所知,HitTesting需要视图中的视觉效果。所以问题的意图没有意义 - 我的新手错误。最终,测试的代码可以放在视图模型中,但在某些时候,起始视觉也必须添加到视图模型中。

对我来说最简单的方法是:

Code-Behind中的

  inkcanvas.PreviewMouseLeftButtonDown += vm.OnPreviewLeftMouseDown;

并在视图模型中:

 public void OnPreviewLeftMouseDown (object sender, MouseButtonEventArgs e)
    { 
        // get visual parent to the inkcanvas. this parent contains all the canvases.
         DependencyObject visualparent = VisualTreeHelper.GetParent((DependencyObject)sender);

         GetVisualHeap( e.GetPosition((UIElement)sender), VisualTreeHelper.GetParent((DependencyObject)sender));
    }

其中vm是viewmodel,而GetVisualHeap是我实际进行命中测试的方法(在SO上有很好的记录)。

希望这有助于某人。我肯定会对更好的解决方案感兴趣。