![](/img/trans.png)
[英]How to Trigger Click Event in WPF User control (Textbox with Button)?
[英]How to trigger an event only when the user ctrl click the lower half of a button?
我想在我的應用程序中實現一些秘密功能,並且只能通過ctrl左鍵單擊按鈕的下半部分來調用它們。 這可以在WPF中實現嗎? 我嘗試創建一個演示應用程序,並且調試未在click事件處理程序中向我顯示光標位置信息。 下面是我的測試代碼。 有任何想法嗎?
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="255.284" Width="313.918">
<Grid>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="81,89,0,0" VerticalAlignment="Top" Width="158" Height="49" Click="button_Click"/>
</Grid>
</Window>
using System.Windows;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{ // <----- set break point here, can't find cursor info in e and sender
}
}
}
您可以使用MouseUp或MouseDown事件,這兩個事件都可以為您提供事件參數中的鼠標位置以及按下的鼠標按鈕。
當在按鈕內部將鼠標按鈕抬起時,將觸發鼠標上移;在按鈕內部被按下時,按下鼠標將觸發(您能猜到嗎?)。
編輯:我只是檢查了MouseDown的詳細信息,您將不得不使用
Point p = e.GetPosition(yourButton);
獲取鼠標相對於按鈕的位置(您可以用任何控件替換yourButton
以獲得鼠標相對於按鈕的位置)
有很多方法可以做到這一點!
除了提供的答案(我認為是正確的)之外,您還可以嘗試布局。 例如,您可以定義一個邊框,其中包含兩個按鈕,用戶會認為其中只有一個按鈕:
<Grid HorizontalAlignment="Center" VerticalAlignment="Center" Width="250" Height="100" >
<Border BorderBrush="Black" BorderThickness="1" MouseEnter="border_MouseEnter" MouseLeave="border_MouseLeave">
<StackPanel>
<Button VerticalAlignment="Top" Height="50" Style="{StaticResource ButtonStyle}" Content="MainButton"></Button>
<Button VerticalAlignment="Bottom" Content="SecretArea" Style="{StaticResource ButtonStyle}" Height="50" Click="Button_Click"></Button>
</StackPanel>
</Border>
</Grid>
通過以您定義的樣式從按鈕上刪除邊框,您將獲得以下內容:
您還可以使用MouseEnter和MouseLeave事件,在用戶將鼠標懸停在邊框上時設置邊框的背景顏色。
無論如何,當用戶單擊秘密區域按鈕時,您可以簡單地處理事件:
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Secret Area");
}
您可以使用Mouse.GetPosition
來獲取相對於按鈕角的光標位置,並將該位置與按鈕的ActualHeight
進行比較:
var pos = Mouse.GetPosition(button);
if(pos.Y >= button.ActualHeight * 0.5)
{
//do something
}
在現有按鈕的下半部分上方添加第二個按鈕,但將其設置為對用戶不可見。
然后,您可以對其點擊處理程序進行編程,以完全按照您的要求進行操作,甚至可以根據需要激活底層可見按鈕的點擊處理程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.