Why do i need to use background color on Grid in order to make button event work?

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-04 19:20:52

问题


Why Grid, StackPanel etc. needs to have background in order to make MouseDown event work properly? If i don't set background then events that are connected to clicking mouse buttons won't trigger at all. After setting background to even transparent color it starts working properly.

What is the purpose of that solution? Is there something going on 'behind' the scene that i don't know about? Does Background setting change more than just background?


回答1:


If you don't set a background, you will click through it, the element below it (probably the Window) will get the events.




回答2:


In order not to click through is to set the background color's A property to 0%. You can do that in the Properties of the controls, click on the Background, you will see R,G,B,A. Give A a zero

<Button Content="OK" Background="#00000000" Width="150"/>

Now you can have a transparent color and capture all events (not click through).

Note, originally I set the color to Black (R=0, G= 0, B= 0). Chaning the A, will change the original color to HEX notation, but it doesn't matter as you can pick any color and make it look transparent.




回答3:


I believe it comes as a result of premise that user won't expect an element to be clicked if it's not visible on the screen.

"Empty" space should not react.

Of course there are exceptions, like list box item, where you do want a reaction even if you didn't actually clicked on a letter, but in between them. There, the template of list box item, has a transparent border to catch mouse events even if user misses the "right" target.

So basically, WPF gives you a mechanism to control what is hit test visible and what's not - and, without affecting behavior of children items. And it's only a Background="Transparent" away.



来源:https://stackoverflow.com/questions/21028895/why-do-i-need-to-use-background-color-on-grid-in-order-to-make-button-event-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!