-1

I'm coding a simple animation that change the label position through a Grid. I tried to use the Sleep method for a Thread, but the animation of the label moving each second is not visible. It just show the label at the final position after a time (3 seconds).

Here's the C# code:

private void BtnUno_Click(object sender, RoutedEventArgs e)
{
        for(int i = 1; i < 4; i++)
        {
            Grid.SetColumn(lblUno, i);
            Thread.Sleep(1000);
        }
}

And the XAML code:

<Window x:Class="AlgoritmoDDA.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:AlgoritmoDDA"
    mc:Ignorable="d"
    Title="Algoritmo DDA" Height="450" Width="700" ResizeMode="NoResize">
<Grid>
    <Grid Name="screen" Height="150" Width="600" VerticalAlignment="Top" Margin="0, 40">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <Label Name="lblUno" Background="Black" Grid.Column="0"/>
    </Grid>

    <Button Name="btnUno" Content="Click Me" Height="34" Width="100"
            VerticalAlignment="Bottom" Margin="0,30"
            FontSize="16"
            Click="BtnUno_Click"/>
</Grid>

lblUno is the label's name. The instruction is called after click a button. I want to understand why it doesn't works, what i'm doing wrong and if is better to use another thing that isn't threads. I hope get not just a fast solution, else a complete solution. Thanks

  • It would be awesome if you could provide a [mcve]. What do you mean by `I implement a thread`? – mjwills Feb 24 '19 at 04:57
  • Never call Thread.Sleep in a UI application. Replace `Thread.Sleep(1000)` with `await Task.Delay(1000)` and declare the Click handler method `async`. – Clemens Feb 24 '19 at 09:07

1 Answers1

-2

I guess you do this by Mainthread so you MainThread gone sleep so don't have time to update GUI

the previous answer add System.Windows.Forms.Application.DoEvents; to the code is telling MainThread to do other jobs in queue and then continue to sleep.

I suggest you not to sleep MainThread that will cause your application to stuck. do this by other Thread than MainThread.

for (int i = 1; i < 4; i++)
{
    Dispatcher.BeginInvoke(DispatcherPriority.SystemIdle, () => { Grid.SetColumn(lblUno, i) } );
    Thread.Sleep(1000);
}