对Button.IsPressed WPF做出反应

时间:2014-10-31 20:54:55

标签: c# wpf xaml

我希望在按下按钮时更改TextBlock,然后在释放按钮时返回上一个状态。

似乎RepeatButton在这里不是一个解决方案,因为它只对自己被保持而不释放做出反应 - 我需要知道它何时被释放,以便我可以运行一个正确的方法将TextBlock返回到其原始状态。绝望,我也尝试循环while(button.IsPressed)(是的,我知道,可怕的想法:()但无济于事 - 代码会挂起(好像IsPressed在按钮释放后没有变为false)。 / p>

有没有办法实现它?提前谢谢。

2 个答案:

答案 0 :(得分:0)

也许不是最干净的方式,但我决定为我的按钮创建多个处理程序:ClickPointerPressedPointerCancelledPointerCaptureLostPointerReleased。前两个用于处理按下的按钮,而后三个用于处理释放。由于推荐,我使用了全部三个:

http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.uielement.pointerreleased

这是因为PointerReleased有时会被按钮释放时触发的其他事件所取代。

答案 1 :(得分:0)

PreviewMouseDown和PreviewMouseUp似乎工作正常,如果您想要左右键单击以获得所需的效果:

public partial class MainWindow : Window
{
    private string TextBlockPreviousState = "";
    public MainWindow()
    {
        InitializeComponent();
        ButtonStatusTextBlock.Text = "foo";
    }

    private void StoreAndUpdate()
    {
        TextBlockPreviousState = ButtonStatusTextBlock.Text;
        ButtonStatusTextBlock.Text = "Button Down";
    }

    private void Restore()
    {
        ButtonStatusTextBlock.Text = TextBlockPreviousState;
    }

    private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        StoreAndUpdate();
    }

    private void Button_PreviewMouseUp(object sender, MouseButtonEventArgs e)
    {
        Restore();
    }
}