按钮缩放边界(条件)

Button scaled boundries(conditions)

大家好,我尝试缩放按钮的大小,代码工作正常,如果我只点击一次,但如果我连续点击按钮多次,按钮不能return其原始大小。 这是代码:

 private void ButtonSearchMedication_OnClick(object sender, RoutedEventArgs e)
    {


            //Assign variation of width in term of begin, end and duration
        DoubleAnimation widthAnimation  =new DoubleAnimation(ButtonSearchMedication.ActualWidth, ButtonSearchMedication.ActualWidth*0.8, new Duration(timeSpan:TimeSpan.FromSeconds(0.2)) );

        //Assign variation of height in term of begin, end and duration
        DoubleAnimation heightAnimation = new DoubleAnimation(ButtonSearchMedication.ActualHeight,ButtonSearchMedication.ActualHeight*0.8, new Duration(timeSpan:TimeSpan.FromSeconds(0.2)));

        //Assign properties to button
        ButtonSearchMedication.BeginAnimation(Button.WidthProperty,widthAnimation);
        ButtonSearchMedication.BeginAnimation(Button.HeightProperty,heightAnimation);
    }

private void ButtonSearchMedication_OnMouseLeave(object sender, MouseEventArgs e) {

            DoubleAnimation widthAnimation = new DoubleAnimation(ButtonSearchMedication.ActualWidth, ButtonSearchMedication.ActualWidth*1.25,new Duration(timeSpan:TimeSpan.FromSeconds(0.2)));
            DoubleAnimation heightAnimation = new DoubleAnimation(ButtonSearchMedication.ActualHeight, ButtonSearchMedication.ActualHeight*1.25,new Duration(timeSpan:TimeSpan.FromSeconds(0.2)));
            ButtonSearchMedication.BeginAnimation(Button.WidthProperty,widthAnimation);
            ButtonSearchMedication.BeginAnimation(Button.HeightProperty,heightAnimation);
        }

我能做些什么来确保每次 MouseLeave 后按钮的大小都变成原来的大小吗?谢谢

鼠标click/mouse离开真的不匹配。您可以不点击离开。

这里无论如何给你一个开始是固定的代码:

const double _width = 200;
const double _height = 100;

void ButtonSearchMedication_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var widthAnimation = new DoubleAnimation(_width * 0.8, TimeSpan.FromSeconds(0.2));
    var heightAnimation = new DoubleAnimation(_height * 0.8, TimeSpan.FromSeconds(0.2));
    buttonSearchMedication.BeginAnimation(WidthProperty, widthAnimation);
    buttonSearchMedication.BeginAnimation(HeightProperty, heightAnimation);
}

void ButtonSearchMedication_PreviewMouseLeftButtonUp(object sender, MouseEventArgs e)
{
    var widthAnimation = new DoubleAnimation(_width, TimeSpan.FromSeconds(0.2));
    var heightAnimation = new DoubleAnimation(_height, TimeSpan.FromSeconds(0.2));
    buttonSearchMedication.BeginAnimation(WidthProperty, widthAnimation);
    buttonSearchMedication.BeginAnimation(HeightProperty, heightAnimation);
}

我决定使用鼠标 down/up 事件,您可以将其更改为 enter/leave 或其他。

如您所见,大小是恒定的,动画仅使用 to 参数(这样在点击事件的情况下多个动作将不会叠加)。如果按钮大小是动态的,那么您将必须在开始动画之前检索并存储原始大小,可能通过使用另一个事件(例如鼠标输入)。