Create a random number and put it in a TextBlock

I created a class that generates a random number:

public class DataGenerator
{
    public void RandomHRValue()
    {
        Random random = new Random();
        int RandomNumber = random.Next(0, 100);
    }
}

Then I created a XAML file and placed the following in Grid:

<TextBlock Name="a" Text="" Width="196" HorizontalAlignment="Center" Margin="183,158,138,56"/>

I did nothing with the file xaml.cs. How can I put a random number in this TextBlockevery 20 seconds?

+4
source share
2 answers

You can use DispatcherTimeras follows:

public MainWindow()
{
     InitializeComponent();
     DispatcherTimer timer = new DispatcherTimer();
     timer.Interval = new TimeSpan(0, 0, 20);
     timer.Start();
     timer.Tick += timer_Tick;
}

void timer_Tick(object sender, EventArgs e)
{
     DataGenerator dg = new DataGenerator();
     a.Text = dg.RandomHRValue().ToString();
}

Also change the type of the method to int:

 public int RandomHRValue()
 {
      Random random = new Random();
      int RandomNumber = random.Next(0, 100);
      return RandomNumber;
 }
+4
source

I cannot comment due to my low reputation, but in response to another answer it would not be better to use the following:

        InitializeComponent();
        DispatcherTimer timer = new DispatcherTimer {Interval = new TimeSpan(0, 0, 5)};
        timer.Start();
        timer.Tick += timer_Tick;

, , , (btw OP )

0

Source: https://habr.com/ru/post/1617127/


All Articles