Search code examples
c#imageuser-interfaceasync-awaitupdating

UWP Updating ui CoreApplication...runasync


This is my first post but I'm seeking for an answer for 2 weeks on every forum. What I want to do is press a button and update an image 3 times with a wait of 3 seconds for example. I'm using the MVVM pattern.

In my view.

                <TextBlock  Margin="0,10,0,0"
                    Text="{Binding MyImageSource}" />
                <Image Source="{Binding MyImageSource}"
                       Width="40"
                       Height="40">
                </Image>
    private async void bt_Click(object sender, RoutedEventArgs e)
    {
        await MyViewmodel.SetCardsBackGround();
    }

Here in my ViewModel I wait set my property I wait and so on. There is one problem the text on my screen updates but the image not. I don't understand my binding works for the text but not for the image.

    public async Task SetCardsBackGround()
    {
        System.Threading.Tasks.Task.Delay(<3 seconds>).Wait(); 
        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        () =>
        {
          MyImageSource = "ms-appx:///Assets/StoreLogo.png";
        });
        System.Threading.Tasks.Task.Delay(<3 seconds>).Wait(); 
        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        () =>
        {
          MyImageSource = "ms-appx:///Assets/StoreLogo1.png";
        });
        System.Threading.Tasks.Task.Delay(<3 seconds>).Wait(); 
        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        () =>
        {
          MyImageSource = "ms-appx:///Assets/StoreLogo2.png";
        });
    });

So my result is :
Wait 3 seconds:
TextBlock = ms-appx:///Assets/StoreLogo.png
Image doesn't appear NOK
Wait 3 seconds:
TextBlock = ms-appx:///Assets/StoreLogo1.png
Image doesn't appear NOK
Wait 3 seconds:
TextBlock = ms-appx:///Assets/StoreLogo2.png
Image appear OK

And I'm really not sure I'm doing this on the right way. You're help would really be appreciated.


Solution

  • Try this:

    public async Task SetCardsBackGround()
    {
        await System.Threading.Tasks.Task.Delay(<3 seconds>); 
        MyImageSource = "ms-appx:///Assets/StoreLogo.png";
        await System.Threading.Tasks.Task.Delay(<3 seconds>); 
        MyImageSource = "ms-appx:///Assets/StoreLogo1.png";
        await System.Threading.Tasks.Task.Delay(<3 seconds>); 
        MyImageSource = "ms-appx:///Assets/StoreLogo2.png";
    });