UWP Change loading state using binding and async functions - asynchronous

I am coming from an Angular 2 and a C# back end background, so for the Angular side of things I am used to working with async functions and code, as well the C# background I understand the base libraries.
I am trying to create a simple page that has a a button, and a loading gif. You click the button the loading gif appears, 10 seconds later it disappears.
I can make the loading start no problem, but the nature of the async code jumps the execution and instantly makes the gif disappear.
How do I go about starting the spinner / making a gif visible, waiting 10 seconds in a non ui-blocking manner, and then finish with a thread-safe way of ending the animation / gif visibility?
View-Model code:
public class LoadingViewModel: INotifyPropertyChanged
{
private Visibility _loadingState;
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public LoadingViewModel()
{
this._loadingState = Visibility.Collapsed;
}
public Visibility LoadingState
{
get {
return this._loadingState;
}
set {
this._loadingState = value;
this.OnPropertyChanged();
}
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
// Raise the PropertyChanged event, passing the name of the property whose value has changed.
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
MainView.xaml.cs:
public LoadingViewModel LoadingViewModel { get; set; }
public MainPage()
{
this.InitializeComponent();
this.LoadingViewModel = new LoadingViewModel();
}
private async Task BeginLoading()
{
LoadingViewModel.LoadingState = Visibility.Visible;
await Task.Factory.StartNew(() =>
{
Task.Delay(TimeSpan.FromSeconds(10));
}).ContinueWith(EndLoadingState);
}
//Updated and works but is there a better way?
private async Task BeginLoading()
{
LoadingViewModel.LoadingState = Visibility.Visible;
await Task.Factory.StartNew(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(10));
await EndLoadingState(); //<-- New EndLoadingState doesn't accept parms
});
}
private async void EndLoadingState(object state)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
LoadingViewModel.LoadingState = Visibility.Collapsed;
});
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
await BeginLoading();
}
And lastly a basic stack panel with my button and image:
<StackPanel Margin="10,144,0,144">
<Button Content="Begin Loading for 10 seconds" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0" Height="157" Width="366" FontSize="22" Background="{x:Null}" BorderThickness="5" BorderBrush="#FF58FF00" Click="Button_Click"/>
<Image HorizontalAlignment="Center" Height="250" VerticalAlignment="Center" Width="250" Margin="0,25,0,0" Stretch="UniformToFill" Source="Assets/LoadingBubbles.gif" Visibility="{x:Bind Path=LoadingViewModel.LoadingState, Mode=TwoWay}"/>
</StackPanel>

First, try using a bool property in your LoadingViewModel instead of Visibility as the latter is a UI attribute. You generally don't want that in your ViewModel. If your target version of Windows 10 is 14393 or higher, you can bind it directly without a BoolToVisibilityConverter. And the binding doesn't need to be TwoWay also.
Visibility="{x:Bind Path=LoadingViewModel.IsLoading, Mode=OneWay}"
Second, XAML binding will actually take care of dispatching the updated value onto the UI thread. So you can also get rid of Dispatcher.RunAsync and have a normal void method
private void EndLoadingState(object state)
{
LoadingViewModel.IsLoading = false;
}
Finally, your BeginLoading method(best to rename it to BeginLoadingAsync) can be simplified to
private async Task BeginLoadingAsync()
{
LoadingViewModel.IsLoading = true;
await Task.Delay(TimeSpan.FromSeconds(10));
EndLoadingState();
}
Hope this helps!

Related

how to animate state transitions in Blazor when rendering a list of object with their own lifecycle?

I know that there is a post closely related to my question (How to animate state transitions in Blazor?).
However, my problem is the following : Consider a list of toasts for instance. I want to display 5 toasts, they can be removed by clicking on them, or they remove themselves when their timers is out.
Code simplified as example.
Component Toasts
#inject ToastService ToastService
<div class="toasts">
#foreach (ToastData data in ToastService.List)
{
<Toast Data="data" />
}
</div>
#code {
protected override async Task OnInitializedAsync()
{
ToastService.OnListChange += RefreshList;
}
public void RefreshList()
{
StateHasChanged();
}
}
ToastService
public class ToastService
{
private List<ToastData > _list;
public List<ToastData > List
{
get
{
var list = _list.Take(5).ToList();
foreach (ToastData data in list)
{
data.StartCountDown();
}
return list;
}
}
public event Action OnListChange;
public ToastService()
{
_List = new List<ToastData >();
}
public async Task CreateToast(ToastData data)
{
_list.Add(data);
OnListChange?.Invoke();
}
public async Task RemoveToast(ToastData data)
{
_list.Remove(data);
OnListChange?.Invoke();
}
}
ToastData
public class ToastData
{
private ToastService _toastService;
private bool _isCountdownStarted;
private System.Timers.Timer _countdown;
public ToastData(ToastService toastService)
{
_toastService= toastService;
}
public void StartCountDown()
{
if (_isCountdownStarted)
return;
_countdown = new System.Timers.Timer(5000);
_countdown.AutoReset = false;
_countdown.Start();
_countdown.Elapsed += RemoveNotification;
_isCountdownStarted = true;
}
public void RemoveNotification()
{
_countdown.Close();
_toastService.RemoveNotification(this);
}
private void RemoveNotification(object source, ElapsedEventArgs args)
{
RemoveNotification();
}
}
Component Toast
<div #onclick="Clicked" class="toast">
Some message on a toast
</div>
#code {
[Parameter] public ToastData Data { get; set; }
public void Clicked()
{
Data.RemoveNotification();
}
}
The above example work fine, cause there's no animation yet.
But now, I want to add an animation of the Toast component. So I modify the ToastData to first call a Hide method, this method will notify the Toast component who will add a CSS class that will animate the removal.
This works fine, until this happen :
Toast component 1 start to animate the removal
Toast component 2 start to animate the removal
Toast 1 is removed, the list is refreshed
Toast 2 is now Toast 1, the animation is gone, and suddenly it disappear
Worst even, a Toast 3 would become Toast 2 and will animate even if not intended to be removed yet.
I understand that Blazor choose to reuse HTML, that's why in the Toasts component, all Toast component will always be the same. That's why I put the logic in the ToastData.
I'm guessing I'm missing something...
Any help or insight appreciated!
When rendering components in a loop, the #key directive attribute is your friend.
It will help Blazor keep the relationship between data and a component instance.
https://learn.microsoft.com/en-us/aspnet/core/blazor/components/?view=aspnetcore-6.0#use-key-to-control-the-preservation-of-elements-and-components

How to use MediaManager plugin and play and pause icon in Xamarin.Forms project

Update:
It's playing well, but when finished playing it's not showing the play button. I have tried I couldn't get it well. Maybe I spiked something else were.
How can I show the play button when a player finished playing?
HomePage.xaml
<Button ImageSource="{Binding PlayIcon}"
Command="{Binding PlayCommand}"
HorizontalOptions="End"
VerticalOptions="End"/>
HomePage.xaml.cs
public HomePage()
{
InitializeComponent();
isPlaying = true;
}
private bool isPlaying;
public bool IsPlaying
{
get { return isPlaying; }
set
{
isPlaying = value;
OnPropertyChanged(nameof(PlayIcon));
}
}
public string PlayIcon { get => isPlaying ? "play.png" : "pause.png"; }
public ICommand PlayCommand => new Command(Play);
private async void Play()
{
if (isPlaying)
{
await CrossMediaManager.Current.Play("file:///android_asset/running.mp3");
IsPlaying = true; ;
}
else
{
await CrossMediaManager.Current.Pause();
IsPlaying = false; ;
}
}
Thank you for your contribution.
to play an asset, use this syntax
private async void PlayButtonClicked(object sender, EventArgs e)
{
// update the button's image
((Button)sender).ImageSource = ImageSource.FromFile("pause.png");
wait CrossMediaManager.Current.Play("file:///android_asset/long-test.mp3");
}
ref: https://github.com/Baseflow/XamarinMediaManager/issues/840
the docs contains a list of events supported by the control, including a MediaItemFinished event

C#, Xamarin Forms: No Custom TextChangedEvent Raised on initialization

I'm creating an Xamarin.Forms MVVM App (only using Android) which needs certain buttons to be outlined red, whenever their text property holds a specific value. (Purpose: alert the user to press the button and select a value, which will change the Button Text Property and therefore remove the red outline)
To achieve this I've create the following documents:
A custom button CButton that extents the default Button:
public class CButton : Button
{
// this Hides the Default .Text-Property
public string Text
{
get => base.Text;
set
{
base.Text = value;
TextChangedEvent(this, new EventArgs());
}
}
// The Raised Event
protected virtual void TextChangedEvent(object sender, EventArgs e)
{
EventHandler<EventArgs> handler = TextChanged;
handler(sender, e);
}
public event EventHandler<EventArgs> TextChanged;
}
A custom behavior makes use of the raised TextChangedEvent
public class ButtonValBehavior : Behavior<CButton>
{
protected override void OnAttachedTo(CButton bindable)
{
bindable.TextChanged += HandleTextChanged;
base.OnAttachedTo(bindable);
}
void HandleTextChanged(object sender, EventArgs e)
{
string forbidden = "hh:mm|dd.mm.yyyy";
if (forbidden.Contains((sender as CButton).Text.ToLower()))
{
//Do when Button Text = "hh:mm" || "dd.mm.yyyy"
(sender as CButton).BorderColor = Color.Gray;
}
else
{
//Do whenever Button.Text is any other value
(sender as CButton).BorderColor = Color.FromHex("#d10f32");
}
}
protected override void OnDetachingFrom(CButton bindable)
{
bindable.TextChanged -= HandleTextChanged;
base.OnDetachingFrom(bindable);
}
}
The relevant parts of the ViewModel look the following:
public class VM_DIVI : VM_Base
{
public VM_DIVI(O_BasisProtokoll base)
{
Base = base;
}
private O_BasisProtokoll _base = null;
public O_BasisProtokoll Base
{
get => _base;
set
{
_base = value;
OnPropertyChanged();
}
}
Command _datePopCommand;
public Command DatePopCommand
{
get
{
return _datePopCommand ?? (_datePopCommand = new Command(param => ExecuteDatePopCommand(param)));
}
}
void ExecuteDatePopCommand(object param)
{
//launch popup
var p = new PP_DatePicker(param);
PopupNavigation.Instance.PushAsync(p);
}
}
The .xmal looks the following (b is the xmlns of the Namespace):
<b:CButton x:Name="BTN_ED_Datum"
Text="{Binding Base.ED_datum, Mode=TwoWay}"
Grid.Column="1"
Command="{Binding DatePopCommand}"
CommandParameter="{x:Reference BTN_ED_Datum}">
<b:CButton.Behaviors>
<b:ButtonValBehavior/>
</b:CButton.Behaviors>
</b:CButton>
This solution works fine whenever the input is caused by user interaction. However, when a Value is assigned during the initialization of the Page no red outline is created, in fact the TextChangedEvent isn't raised. By using breakpoints I noticed that during initialization the Text Property of CButton is never set, eventhough it actually will be in the view.
Despite fiddling around with my solution I cannot make this work on initialization. I tried to work around this issue by outlining every button by default in their constructor, however this will outline every button red, even when their text value doesn't require them to be.
How can I achieve my initial goal?
Many thanks in advance!
It's been a while but if I recall correctly what I ended up doing was:
Changing the new Text-Property of my custom Button to CText and
Making sure that I have Mode=TwoWay activated for any Element, that doesn't have it enabled by default. (Look up Binding modes on msdn for more)
making CText a bindable property of CButton
My custom button now looks the following:
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace EORG_Anton.Model
{
public class CButton : Button
{
public static readonly BindableProperty CTextProperty =
BindableProperty.Create(nameof(CText),
typeof(string),
typeof(CButton),
default(string),
BindingMode.TwoWay,
propertyChanged: OnTextChanged);
private static void OnTextChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (CButton)bindable;
var value = (string)newValue;
control.CText = value;
}
public string CText
{
get => base.Text;
set
{
base.Text = value;
TextChangedEvent(this, new EventArgs());
}
}
protected virtual void TextChangedEvent(object sender, EventArgs e)
{
EventHandler<EventArgs> handler = TextChanged;
handler(sender, e);
}
public event EventHandler<EventArgs> TextChanged;
}
}

Xamarin.Forms Update Label Text From a Service

I have a Label on MainPage.xaml. I can edit Label Text from MainPage.xaml.cs.
There is a foregroung service running as well. There is function in this service to check a value from SQLite DB for every 10 secs. When value changes, Label text should be updated. I tried binding but it is a bit confusing. I manage updating by using like this: (foreground service timer changes App.SomeValue)
protected override void OnAppearing()
{
lblSyncID.Text = App.SomeValue;
}
But I need to see changes without OnAppearing or any other navigation change.
EDIT:
With #Jason's suggestion I used Messaging Center (and also binding) and it works now:
MainPage.xaml:
<Label Text="{Binding AppWaitingRecordValue}" ...
MainPage.xaml.cs:
public partial class MainPage : ContentPage
{
private string appWaitingRecordValue;
public string AppWaitingRecordValue
{
get { return appWaitingRecordValue; }
set
{
appWaitingRecordValue = value;
OnPropertyChanged(nameof(AppWaitingRecordValue));
}
}
public MainPage()
{
InitializeComponent();
BindingContext = this;
AppWaitingRecordValue = "0";
MessagingCenter.Subscribe<App>((App)Application.Current, "AppRecord", (sender) =>
{
AppWaitingRecordValue = App.recordWaiting.ToString();
});
}
.
.
TimestampService.cs (from Project.Android):
// get i from DB
App.recordWaiting = i;
Xamarin.Forms.MessagingCenter.Send<App>((App)Xamarin.Forms.Application.Current, "AppRecord");

DisplayAlert from ViewModel not displaying

I need to display DisplayAlert from the View Model, however its simply doesn't display. Is there some other way how to display alert from the VM? The permission is true so that works.
private async Task TakePicture()
{
await Permission();
var imageSource = Application.Current.MainPage.DisplayActionSheet(AppResources.AlertNewPhoto, AppResources.AlertNewPhoto, AppResources.AlertGallery);
if (imageSource.Result == AppResources.AlertNewPhoto)
}
You can change your constructor of ViewModel like following code.
public PersonsViewModel(ContentPage page){
page.DisplayAlert("info","test","Ok");
}
In your Layout background code, you can use it following code.
public partial class MainPage : ContentPage
{
PersonsViewModel personsViewModel;
public MainPage()
{
InitializeComponent();
personsViewModel = new PersonsViewModel(this);
this.BindingContext = personsViewModel;
}
If you can use plugin, you can use ACR.UserDialogs. https://github.com/aritchie/userdialogs
I solved this problem using events
public MainPageVewModel()
{
Application.Current.MainPage.Loaded += LoadCards;
}
private async void LoadCards(object sender, EventArgs e)
{
// your code on View Loaded
await Application.Current.MainPage.DisplayAlert("working alert", "alert", "ok");
}

Resources