Mayra García
Mayra García

Reputation: 13

How to change a fill color for an ellipse in discrete steps in c# WPF

I have a list of boolean values named Sequence. I want to change the color of a shape based on the values of the list, that is, I want to iterate through the values of the list and fill the shape with a certain color (for example yellow) every time I stumble upon a True value and change the color of the filling (to blue) every time I stumble upon a False value. I have tried doing it like this:

foreach(bool element in Sequence)
{
    if(element){ ellipse.Fill = new SolidColorBrush(Colors.Yellow); }
    else{ ellipse.Fill = new SolidColorBrush(Colors.Blue); }
    int milisecond = 200;
    Thread.Sleep(miliseconds);
}

But still the colors won't alternate.

Here's the XAML:

`<Ellipse x:Name="elipse" Height="100" Margin="151,52,0,0" Stroke="Black" Width="100" /> `

Do I need a trigger?, What am I doing wrong?. Thank you in advance, and excuse my bad english if something seems funny.

Upvotes: 1

Views: 1830

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61339

foreach(bool element in Sequence)
{
    if(element){ ellipse.Fill = new SolidColorBrush(Colors.Yellow); }
    else{ ellipse.Fill = new SolidColorBrush(Colors.Blue); }
    int milisecond = 200;
    Thread.Sleep(miliseconds);
}

Runs synchronously on the UI thread. Thus, the UI never gets a chance to update the color. Use a timer instead.

Of course, then you can't foreach, as you'd have to keep track of your current index. One way around that would be to keep your current code but replace the Thread.Sleep with an await Task.Delay.

(apologies from Peter Duniho, who added this code example, but this answer just seemed to be crying out for one):

<edit>
The async based one would look something like this (and IMHO is preferable to using a timer):

foreach (bool element in Sequence)
{
    ellipse.Fill = new SolidColorBrush(element ? Colors.Yellow : Colors.Blue);
    await Task.Delay(200);
}

Of course, to be able to use await, the method in which it's used needs to be declared as async. Unfortunately, the original question does not provide the full method nor its signature, but presumably the OP can research the use of async methods themselves and see how to convert.
</edit>

The whole use case seems like it should be re-designed, but one of those solutions should get you farther down this path. Remember, if you are writing code-behind, you are probably doing it wrong.

Upvotes: 1

Related Questions