Reputation: 600
I have created a class which generates a random number:
public class DataGenerator
{
public void RandomHRValue()
{
Random random = new Random();
int RandomNumber = random.Next(0, 100);
}
}
I have then created a XAML file and put the following within the Grid
:
<TextBlock Name="a" Text="" Width="196" HorizontalAlignment="Center" Margin="183,158,138,56"/>
I haven't done anything to the xaml.cs
file. How would I go about putting a random number into that TextBlock
every 20 seconds?
Upvotes: 4
Views: 5247
Reputation: 39956
You can use DispatcherTimer
like this:
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 method type to int:
public int RandomHRValue()
{
Random random = new Random();
int RandomNumber = random.Next(0, 100);
return RandomNumber;
}
Upvotes: 4
Reputation: 875
I can't comment due to my low reputation, but in response to the other answer, would it not be better to use the following?
InitializeComponent();
DispatcherTimer timer = new DispatcherTimer {Interval = new TimeSpan(0, 0, 5)};
timer.Start();
timer.Tick += timer_Tick;
If this is wrong, can you say why, so I, myself, can get some feedback (btw OP and I are working together on this)
Upvotes: 0