Тестирование попадания на дочернем элементе InkCanvas

Я добавил кнопку в InkCanvas с помощью кода программной части. По причинам, которые я не могу понять,

    HitTestResult result = VisualTreeHelper.HitTest(pe.InkCanvas.Children[2], point_MouseDown);

где кнопка имеет индекс 2, всегда приводит к нулевому результату, когда я нажимаю кнопку.

Кто-нибудь знает, как определить, был ли нажат дочерний элемент?

Любая помощь будет оценена. (Да, я безуспешно искал в Интернете. Прошу прощения, если это покажется глупым вопросом).

Система: Windows 7, .net4.0 WPF C#

Изменить: если я сделаю то же самое, где Children[0] является RichTextBox, то вышеприведенный HitTest вернет ненулевое значение. Кто-нибудь знает, почему?

Изменить: как RichTextBox, так и кнопка добавляются в код программной части, XAML:

 <Grid Height="{x:Static local:pe.heightCanvas}" >

            <!--NotepadCanvas. Canvas used to place user writing lines and borders.-->
            <Canvas Name="NotePadCanvas" Panel.ZIndex="0"
                     Width="{x:Static local:pe.widthCanvas}" 
                     Height="{x:Static local:pe.heightCanvas}" 
                     Background="{Binding documenttype, Converter={StaticResource inkCanvasBackgroundConverter}}" />

            <!--BackgroundCanvas. Canvas used for special highlighting of seleted items-->
            <Canvas Name="BackgroundCanvas" Panel.ZIndex="1"
                     Width="{x:Static local:pe.widthCanvas}" 
                     Height="{x:Static local:pe.heightCanvas}" 
                     Background="Transparent" />

            <!--FormsCanvas. Canvas used to place formatted text from lists, etc.-->
            <Canvas Name="FormsCanvas" Panel.ZIndex="2"
                     Width="{x:Static local:pe.widthCanvas}" 
                     Height="{x:Static local:pe.heightCanvas}" 
                     Background="Transparent" />

            <!--TranscriptionCanvas. Canvas used to place recognized ink from the InkAnalyzer-->
            <Canvas Name="TranscriptionCanvas" Panel.ZIndex="3"
                     Width="{x:Static local:pe.widthCanvas}" 
                     Height="{x:Static local:pe.heightCanvas}" 
                     Background="Transparent" />

            <!--InkCanv. Top most canvas used to gather handwritten ink strokes from the user. EditingMode="Ink"   Gesture="OnGesture" -->
            <local:CustomInkCanvas x:Name="InkCanvas" Panel.ZIndex="4" 
                       Width="{x:Static local:pe.widthCanvas}"
                       Height ="{x:Static local:pe.heightCanvas}" 
                       Background="Transparent" 
                       AllowDrop="True"  Drop="InkCanvas_Drop"/>

        </Grid>

person Alan Wayne    schedule 10.06.2014    source источник
comment
не могли бы вы поделиться своим деревом xaml? так что мы можем посмотреть и попытаться смоделировать.   -  person pushpraj    schedule 11.06.2014


Ответы (1)


Это работает, но кажется запутанным, и я не знаю, почему кнопка отображается как TextBlock:

...........

  Button btn = new Button();
        btn.Name = "Cancel";
        btn.Content = "Cancel";
        btn.Background = Brushes.Red;
        btn.Width = 50;
        btn.Height = 25;
        btn.RenderTransform = new System.Windows.Media.TranslateTransform(pe.InkCanvas.ActualWidth-btn.Width,topmargin);

        btnCancel = btn;
        pe.InkCanvas.Children.Add(btnCancel);

Затем в PreviewMouseLeftButtonDown() (код немного изменен с сайта Microsoft) .......

// Clear the contents of the list used for hit test results.
                hitResultsList.Clear();


                // Set up a callback to receive the hit test result enumeration.
                VisualTreeHelper.HitTest(pe.InkCanvas, null,
                    new HitTestResultCallback(MyHitTestResult),                        new PointHitTestParameters(point_MouseDown));

                for (int i = 0; i < hitResultsList.Count; i++)
                {
                    TextBlock tb = hitResultsList[i] as TextBlock;
                    if (tb == null) continue;
                    if (tb.Text == "Cancel")
                    {
                        Cancel_Click(); 
                    }
                }

..................................................

List<DependencyObject> hitResultsList = new List<DependencyObject>();

    // Return the result of the hit test to the callback. 
    public HitTestResultBehavior MyHitTestResult(HitTestResult result)
    {
        // Add the hit test result to the list that will be processed after the enumeration.
        hitResultsList.Add(result.VisualHit);

        // Set the behavior to return visuals at all z-order levels. 
        return HitTestResultBehavior.Continue;
    }

Есть ли способ лучше? И почему кнопка отображается как TextBlock?

person Alan Wayne    schedule 11.06.2014