You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have several MVVM projects with async methods that update properties in the page's ViewModel. The XAML controls use x:Bind to those properties. The problem is that propagating the property change directly with SetProperty will trigger an exception if invoqued from a thread other than the UI thread. The workarround I devised is to warp it in an action call as follows:
public partial class MainViewModel : ObservableRecipient
{
// save a reference to the UI SynchronizonContext.
readonly SynchronizationContext? UIContext = SynchronizationContext.Current;
// create a wrapper
void UIPost(SendOrPostCallback action) => UIContext?.Post(action, null);
public String? MyPropertyStr
{
get => myPropertyStr;
// call the wrapper as follows
set => UIPost( _ => { SetProperty(ref myPropertyStr, value); });
}
String? myPropertyStr= null;
// constructor, other methods and prpoerties
}
It is a bit ackward but works. This must be extremely common scenario. I wonder if I'm missing something or there is a more elegant/eficient way to work in this situation. I'm aware of Task ontinuations that can bounce back in the UI thread, but in many cases the async mthods are not started in the UI thread, or are indirectly started by other async methods.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I have several MVVM projects with async methods that update properties in the page's ViewModel. The XAML controls use x:Bind to those properties. The problem is that propagating the property change directly with SetProperty will trigger an exception if invoqued from a thread other than the UI thread. The workarround I devised is to warp it in an action call as follows:
It is a bit ackward but works. This must be extremely common scenario. I wonder if I'm missing something or there is a more elegant/eficient way to work in this situation. I'm aware of Task ontinuations that can bounce back in the UI thread, but in many cases the async mthods are not started in the UI thread, or are indirectly started by other async methods.
Beta Was this translation helpful? Give feedback.
All reactions