WPF Rectangle does not have a Click event

房东的猫 提交于 2019-11-27 14:32:14

问题


It seems that the WPF Rectangle shape does not have the Click event defined. What am I supposed to use instead?

It does have MouseUp, but it's not quite the same behavior.


回答1:


If you're not happy with MouseDown and MouseUp, perhaps you could just put the Rectangle in a Button and handle the Button's Click event?

<Button>
    <Button.Template>
        <ControlTemplate>
            <Rectangle .../>
        </ControlTemplate>
    </Button.Template>
</Button>

It really depends with the behavior you're after. Please elaborate if needs be.




回答2:


To add click handing to a Rectangle itself, you can use the InputBindings property:

<Rectangle Fill="Blue" Stroke="Black">
    <Rectangle.InputBindings>
        <MouseBinding Gesture="LeftClick" Command="{Binding FooCommand}"/>
    </Rectangle.InputBindings>
</Rectangle>

This will cause the FooCommand to be executed when the rectangle is clicked. Handy if you're using MVVM!




回答3:


I was looking for the related DoubleClick event and came across this suggestion to simply embed the object of interest in a ContentControl.

Here is their example (with a border, which also did not support click/double click).

<ContentControl MouseDoubleClick="OnDoubleClick">
    <Border Margin="10" BorderBrush="Black" BorderThickness="2">
        <Grid Margin="4">
            <Rectangle Fill="Red" />
            <TextBlock Text="Hello" FontSize="15" />
        </Grid>
    </Border>
</ContentControl>



回答4:


Rectangle has event Tapped, which works fine. In designing universal apps for Windows 8.1, there are new events. Tapped, DoubleTaped, RightTapped and Holding.



来源:https://stackoverflow.com/questions/1068979/wpf-rectangle-does-not-have-a-click-event

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