Monday, June 2, 2008

[Silverlight] Events on a Canvas with no set background color...

It's funny, both myself and another girl at work bumped into this same issue today while working on unrelated projects.

It seems that if you wish to set up events on a Canvas then you MUST set the Background property for the event to trigger when clicking ANYWHERE on the Canvas. If you do not setup a background, then the only time the event will be registered on the Canvas is if the user happens to click on a visible child of that Canvas.

By default the Canvas.Background property is set to null. Now, I imagine that this has the possibility to be rendered differently depending on what is interpreting the xaml. I noted that you can set the background to "transparent" [which is different then null], and while the Canvas will look identical to the default null value, the events will be correctly registered when you click anywhere within the canvas.

Canvas eventWrap = new Canvas();
eventWrap.Background = new SolidColorBrush(Colors.Transparent);
eventWrap.MouseEnter += new MouseEventHandler(showTooltip);
eventWrap.MouseLeave += new MouseEventHandler(hideTooltip);
eventWrap.Children.Add(myWeirdShapedPolygon);
This makes sense when you think about it, since it may be the case that you do not want the events to trigger when mousing over 'unused' portions of the canvas space. I just thought it was interesting to note that ((Background == null) != (Background == Colors.Transparent))




No comments: