使用 DispatcherTimer 显示随机数 [英] Displaying random numbers with a DispatcherTimer

查看:68
本文介绍了使用 DispatcherTimer 显示随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找答案,但似乎没有一个适合我的问题.

I've been looking for an answer but none seem to fit my question.

我正在尝试调整 MvVM 方法,但我认为我没有完全理解它..

I am trying to adapt the MvVM method, but I dont think I fully understand it..

我正在尝试在 WPF 中创建 RPM 显示.

I'm trying to create an RPM display in WPF.

我希望它显示一个数字(0-3000 之间)并每秒更新这个数字(到 TextBlock 中).

I want it to display an number (between 0-3000) and update this number every second (into a TextBlock).

我创建了一个新类,我尝试在其中创建 DispatcherTimer 和 Random 生成器,然后将其放入 UI TextBlock.

I have created a new class where I try to create a DispatcherTimer and Random generator and then put that in the UI TextBlock.

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Threading;

namespace Aldeba.UI.WpfClient
{
    public class GenerateRpm
    {
        public GenerateRpm()
        {
            DispatcherTimer timer = new DispatcherTimer
            {
                Interval = new TimeSpan(0, 0, 5)
            };
            timer.Start();
            timer.Tick += Timer_Tick;
        }
        public int RandomValue()
        {
            Random random = new Random();
            int RandomRpm = random.Next(0, 3001);
            return RandomRpm;
        }
        void Timer_Tick(object sender, EventArgs e)
        {
            MainWindow mainWindow = new MainWindow();

            GenerateRpm rpm = new GenerateRpm();
            mainWindow.RpmDisplayLabel.Text = rpm.RandomValue().ToString();
        }
    }
}

我的 MainWindow.xaml.cs 看起来像...

My MainWindow.xaml.cs looks like...

   /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = new MainWindowViewModel();
            this.DataContext = new GenerateRpm();
        }
    }
}

我是否需要将 datacontext 添加到我想要访问的所有类(例如绑定)?

Do I need to add datacontext to all classes I want to access (for bindings for an example)?

这是我希望 Rpm 在第二个 TextBlock 中显示的 MainWindow.

This is the MainWindow where I want the Rpm displayed in the second TextBlock.

<StackPanel Orientation="Horizontal" Grid.Row="0" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center">
            <TextBlock Text="RPM:" Style="{StaticResource RpmDisplay}" />
            <TextBlock x:Name="RpmDisplayLabel" Text="{Binding }" Style="{StaticResource RpmDisplay}" />
        </StackPanel>

我错过了什么和/或做错了什么才能做到这一点?

What am I missing and/ or doing wrong to be able to do this?

推荐答案

使用如下所示的视图模型,其公共属性由计时器循环更新.

Use a view model like shown below, with a public property that is cyclically updated by the timer.

确保属性设置器触发更改通知,例如INotifyPropertyChanged 接口的 PropertyChanged 事件.

Make sure the property setter fires a change notification, e.g. the PropertyChanged event of the INotifyPropertyChanged interface.

public class MainWindowViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private readonly Random random = new Random();

    public MainWindowViewModel()
    {
        var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
        timer.Tick += Timer_Tick;
        timer.Start();
    }

    private int randomRpm;

    public int RandomRpm
    {
        get { return randomRpm; }
        set
        {
            randomRpm = value;
            PropertyChanged?.Invoke(
                this, new PropertyChangedEventArgs(nameof(RandomRpm)));
        }
    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        RandomRpm = random.Next(0, 3001);
    }
}

将视图模型类的实例分配给 MainWindow 的 DataContext:

Assign an instance of the view model class to the MainWindow's DataContext:

public MainWindow()
{
    InitializeComponent();

    DataContext = new MainWindowViewModel();
}

在视图中,将一个元素绑定到视图模型属性:

In the view, bind an element to the view model property:

<TextBlock Text="{Binding RandomRpm}"/>

这篇关于使用 DispatcherTimer 显示随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆