Question

I have a WPF canvas in which I want to display different color Rectangles (stored in a multi-dimensional array) every x miliseconds.

Random rnd = new Random();

foreach (var i in Enumerable.Repeat(1, 100))
{
    _rectGrid[rnd.Next(0, 30), rnd.Next(0, 30)].Fill = new SolidColorBrush(Colors.Blue);
    Thread.Sleep( 100 );
    // refresh somehow here?
}

This works, but I don't see it update in real time since it is in the MainWindow constructor.

Clearly the Rectangles have to be created in the GUI thread, but if I create a Timer to change the colors it's in a different thread.

Can I create a multi-dimensional array of values and bind the values to the colors in the Rectangle array so I can access them from another thread? And if I do that, how do I tell the GUI thread to redraw?

Maybe it would be simpler to have a button the user clicks first so this doesn't happen in the constructor?

EDIT:

The DispatcherTimer worked great. Why MS has a separate class for this is beyond me.

enter image description here

Here is the source I used it for.

Was it helpful?

Solution

You could use the DispatcherTimer like this:

    public MainWindow()
    {
        InitializeComponent();

        DispatcherTimer t = new DispatcherTimer();
        t.Tick += t_Tick;
        t.Interval = new TimeSpan(0, 0, 0, 0, 300);
        t.Start();
    }
    Random r = new Random();
    void t_Tick(object sender, EventArgs e)
    {
        byte[] rnd = new byte[4];
        r.NextBytes(rnd);
        this.Background = new SolidColorBrush(Color.FromArgb(rnd[0], rnd[1], rnd[2], rnd[3]));
    }

OTHER TIPS

you can try using ContentRendered event of window.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top