0

I have a grid like this:

    <Grid>
        <WrapPanel Name="wrap1"/>
        <Canvas Name="canvas1" Background="LightGray" Opacity="0.5"/>    
    </Grid>

And I want to be able to:

  • capture click events for the WrapPanel buttons
  • capture mouseLeftButtonDown, mouseLeftButtonUp, mouseMove events for the Canvas

WrapPanel Button PreviewMouseLeftButtonDown and Click doesn't work. Also putting Canvas inside WrapPanel or WrapPanel inside Canvas doesn't work.

2 Answers 2

1

Your WrapPanel and Canvas are not in a parent / child relationship in the VisualTree. The WrapPanel does not contaim the Canvas, so the mouse events do not bubble up. You need to contain the Canvas in the WrapPanel and then the events should be available to both.

Edit:

Here is my code that fires both events (I also bound my Canvas width/height to the containing WrapPanel so it would fill the panel):

<WrapPanel Name="wrap1" MouseLeftButtonDown="wrap1_MouseLeftButtonDown">
    <Canvas Name="canvas1" 
        Width="{Binding ElementName=wrap1, Path=ActualWidth}" 
        Height="{Binding ElementName=wrap1, Path=ActualHeight}" 
        Background="LightGray" Opacity="0.5"
        MouseLeftButtonDown="canvas1_MouseLeftButtonDown"/>
</WrapPanel>

Remeber that Preview events are top down in the VisualTree where as non-preview events are bottom up, so if you use the Preview events, the WrapPanel events will fire first, but this code will fire the Canvas event first.

2
  • If I do so canvas don't get any mouse input.
    – Cobold
    Commented Aug 17, 2011 at 21:18
  • I tested this and it works fine, you need to make sure that your Canvas has a size set, as by deafult it will not strech to fill the WrapPanel. Commented Aug 18, 2011 at 14:13
0

EDIT: You should attach to the click events of each button in your WrapPanel then. If they are added dynamically, then attach the event before adding it to the wrap panel.

1
  • Sorry. I misread your question. You should attach to the click events of each button in your WrapPanel then. If they are added dynamically, then attach the event before adding it to the wrap panel.
    – Tejs
    Commented Aug 17, 2011 at 21:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.