0

how could I change my Label content to random letter by using DispatcherTimer C#? My DispatcherTimer doesn't execute Letter_Tick() function :|

My MainWindow.xaml

<Label x:Name="myLbl" Content="" FontSize="108" HorizontalContentAlignment="Center"/>

My main class (MainWindow.xaml.cs)

    public MainWindow()
    {
        InitializeComponent();
        letterRandomizer ob = new letterRandomizer(myLbl);
    }

And my letterRandomizer class

class letterRandomizer
{
    Random rand = new Random();
    string newLetter = "";
    Label MyLbl;
    
    DispatcherTimer letter = new DispatcherTimer();
    
    public letterRandomizer(Label myLbl)
    {
        this.MyLbl = myLbl;
        letter.Tick += Letter_Tick;
        letter.Interval = TimeSpan.FromSeconds(2);
    }

    private void Letter_Tick(object sender, EventArgs e)
    {
        MyLbl.Content = "";
        newLetter = Convert.ToChar(rand.Next(65, 90)).ToString();
        MyLbl.Content = newLetter;
    }

}
Liryk
  • 23
  • 5
  • 2
    Add `letter.Start();` to your `letterRandomizer` constructor - you forgot to start your DispatcherTimer – Quercus Sep 17 '21 at 07:01
  • Wow, @Quercus that was obvious mistake, thanks for help – Liryk Sep 17 '21 at 07:03
  • 1
    You should also consider implementing the MVVM pattern. Instead of passing a reference to a UI element to the LetterRandomizer class, the class should become a "view model" by exposing a public property like `public string Letter`. You would assign an instance of the LetterRandomizer class to the DataContext of the MainWindow, like `DataContext = new LetterRandomizer();` and the UI would bind to the view model property like `` or ``. – Clemens Sep 17 '21 at 07:19
  • 1
    In order to update the UI, LetterRandomizer would implement the INotifyPropertyChanged interface and fire the PropertyChanged event whenever the Letter property changes. – Clemens Sep 17 '21 at 07:20

0 Answers0