移动按钮,然后在1秒后自动返回该位置

时间:2015-08-26 08:18:47

标签: c# wpf

我正在使用wpf c#,我有一个按钮,我希望当我点击它时按钮向右移动一点然后1秒后按钮会自动返回到该位置, 我的问题是当我点击按钮时没有任何反应。  这是我的代码:

    private void yellowBox_Click(object sender, RoutedEventArgs e)
    {


        yellowBox.Margin = new Thickness(185, 61, 0, 0);

        for (int i = 0; i <= 1; i++)
        {


            yellowBox.Margin = new Thickness(140, 61, 0, 0);
            System.Threading.Thread.Sleep(1000);
        }



    }

3 个答案:

答案 0 :(得分:0)

你需要更新布局......你可能会做这样的事情来设置边距后强制更新:

yellowBox.Dispatcher.Invoke(() => {}, DispatcherPriority.Render);

或者您可以让调度程序直接在渲染线程上设置边距(在多线程场景中需要):

yellowBox.Dispatcher.Invoke(
          () => { yellowBox.Margin = new Thickness(140, 61, 0, 0); },
          DispatcherPriority.Render
      );

然而,最好使用具有自己的线程的动画并自动更新布局

答案 1 :(得分:0)

一种方法是使用DispatcherTimer。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfTest2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();

        public MainWindow()
        {
            InitializeComponent();
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 1);

        }

        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            Button1.Margin = new Thickness(185, 61, 0, 0);
            dispatcherTimer.Stop();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            dispatcherTimer.Start();
            Button1.Margin = new Thickness(140, 61, 0, 0);

        }
    }
}

答案 2 :(得分:0)

你可以试试这个,但在我看来,使用动画更好......

private void yellowBox_Click(object sender, RoutedEventArgs e) {
    yellowBox.Margin = new Thickness(185, 61, 0, 0);

    Task.Factory.StartNew(() => {
        Thread.Sleep(1000);
        yellowBox.Dispatcher.Invoke((Action)(() => {
            yellowBox.Margin = new Thickness(0);
        }));
        yellowBox.Margin = new Thickness(0);
    });
}