C# - 每秒刷新矩形宽度

时间:2017-05-09 15:36:25

标签: c# wpf user-interface time refresh

我试图制作一个应用程序(大学),它显示两个代表时钟的矩形。我有两个矩形,一个代表秒,另一个分钟。必须每秒调整宽度以对应时间。

public partial class MainWindow : Window
{
        Rectangle rectMinuut = new Rectangle();
        Rectangle rectSeconde = new Rectangle();
    public MainWindow()
    {
        InitializeComponent();

        rectMinuut.Stroke = new SolidColorBrush(Colors.Black);
        rectSeconde.Stroke = new SolidColorBrush(Colors.DarkBlue);
        rectSeconde.Fill = new SolidColorBrush(Colors.DarkBlue);
        rectMinuut.Fill = new SolidColorBrush(Colors.Black);
        rectSeconde.Height = 100;
        rectMinuut.Height = 100;
        var date = DateTime.Now;
        int widthMinute = date.Minute;
        int widthSecond = date.Second;
        rectMinuut.Width = widthMinute;
        rectSeconde.Width = widthSecond;
        Canvas.SetTop(rectMinuut, 50);
        Canvas.SetTop(rectSeconde, 150);
        paperCanvas.Children.Add(rectSeconde);
        paperCanvas.Children.Add(rectMinuut);

        Timer timer = new Timer();
        timer.Interval = (1000); 
        timer.Elapsed += new ElapsedEventHandler(timer_Tick);
        timer.Start();
    }
    private void timer_Tick(object sender, ElapsedEventArgs e)
    {
        //refresh here... 
        var date = DateTime.Now;
        int widthMinute = date.Minute;
        int widthSecond = date.Second;
        rectMinuut.Width = widthMinute;
        rectSeconde.Width = widthSecond;
    }
}}

我尝试了不同的选项,但在timer_Tick方法中为rectMinuut.Width分配新值时,我的应用程序总是崩溃。

编辑:正确答案:

using System.Windows.Threading;
public partial class MainWindow : Window
{
    private DispatcherTimer timer = new DispatcherTimer();
    public MainWindow()
    {
        InitializeComponent();
        timer.Interval = TimeSpan.FromMilliseconds(200); //200ms, because code takes time to execute too
        timer.Tick += timer_Tick;
        timer.Start();

    }
    private void timer_Tick(object sender, EventArgs e)
    {
        //refresh here... 

        Rectangle rectMinuut = new Rectangle();
        Rectangle rectSeconde = new Rectangle();
        rectMinuut.Stroke = new SolidColorBrush(Colors.Black);
        rectSeconde.Stroke = new SolidColorBrush(Colors.DarkBlue);
        rectSeconde.Fill = new SolidColorBrush(Colors.DarkBlue);
        rectMinuut.Fill = new SolidColorBrush(Colors.Black);
        rectSeconde.Height = 100;
        rectMinuut.Height = 100;
        var date = DateTime.Now;
        int widthMinute = date.Minute * 2; //increase/scale width
        int widthSecond = date.Second * 2;
        rectMinuut.Width = widthMinute;
        rectSeconde.Width = widthSecond;
        Canvas.SetTop(rectMinuut, 50);
        Canvas.SetTop(rectSeconde, 150);
        paperCanvas.Children.Add(rectSeconde);
        paperCanvas.Children.Add(rectMinuut);
    }
}

}

0 个答案:

没有答案