<!-- This is a template for new feature or API proposals.
For example you can u…se this to propose a new API on an existing type, or an idea for a new UI control.
For feature proposals related to UWP or the app models, please open an issue on the Project Reunion repository: https://github.com/microsoft/ProjectReunion
It's fine if you don't have all the details: you can start with the Summary and Rationale.
This link describes the WinUI feature/API proposal process:
https://github.com/Microsoft/microsoft-ui-xaml/blob/master/docs/feature_proposal_process.md
-->
# Proposal: implicit DispatcherQueue support for x:Bind
## Summary
Add automatic (possibly optional) dispatching to the `DispatcherQueue` instance for the current UI thread in the `_BindingsTracking` type and to the necessary internal WinUI paths (eg. to deal with collection changed UI updates), specifically in the [`PropertyChanged`](https://docs.microsoft.com/dotnet/api/system.componentmodel.inotifypropertychanged.propertychanged) event handler and the [`CollectionChanged`](https://docs.microsoft.com/dotnet/api/system.collections.specialized.inotifycollectionchanged.collectionchanged). This would completely reverse the chain of responsability for proper thread dispatching from the viewmodel side to the UI side, and make the whole thing much more resilient and flexible.
A similar concept would apply to other events handled by code within WinUI.
The core idea is this: it should be responsability of an event _handler_ to dispatch to whatever synchronization context it needs, _not_ to the object _raising_ the event. Specifically because if you have multiple listeners on different threads, the latter simply will never work anyway. And in general, objects raising events shouldn't need to account for who's listening to them.
## Details
> **Note:** what follows is just the details for the `PropertyChanged` event specifically, not the others. I'll describe this one since it's more "easily" addressed by looking at the `x:Bind` codegen, whereas the others would likely need some tweaks in the code within WinUI dealing with those events. The idea in general is still the same though: WinUI as a framework should automatically deal with dispatching when handling notification events tied to the UI.
Handling the synchronization context for the `PropertyChanged` event in viewmodels has always been a major pain point when working with MVVM. There have been a variety of different solutions proposed, but each with their shortcomings, namely:
- Lots of overhead in the viewmodels to deal with dispatching to the "UI thread". This also breaks modularity as a viewmodel should conceptually just be a .NET Standard and portable component, where the term "UI thread" has no actual meaning. This should be purely a UI-related aspect that the viewmodels should not really be concerned with.
- Single-context solutions involve capturing a synchronization context from the viewmodel and dispatching there when raising the `PropertyChanged` event. Again this has two issues: for one it's not really flexible as it wouldn't work in case the same observable object is being displayed in different ways across more than a single window (where two different UI threads would be used), and the second issue is that it would inject purely platform dependent code back into a more abstract layer, i.e. the viewmodel.
- Even when using dependency injection to keep the viewmodels technically platform agnostic, this still adds a lot of potentially unnecessary overhead and complexity to what should be a pretty simple implementation of the `INotifyPropertyChanged` interface, plus again I'd argue that conceptually the UI thread dispatching should only be relegated to the actual platform dependent code. From the point of view of a .NET Standard component, individual threads should (generally) not matter much.
The proposed solution is to completely flip this over and add a simple extension to the codegen for `x:Bind` (pinging @MikeHillberg about this) to allow for a more general solution to this issue, built right into the framework itself.
The advantages here would be multiple, as mentioned above as well:
- Less overhead and complexity in the viewmodels, and increased code modularity 🚀
- Less error prone code ✨
- More flexible results, with supports for an arbitrary number of receiving UI threads 🧰
## Implementation
Consider this simple viewmodel (not implemented, it doesn't matter here):
```csharp
public class MainPageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public string Text { get; set; }
}
```
And this XAML snippet:
```xml
<Page
x:Class="XBindSample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XBindSample">
<Page.DataContext>
<local:MainPageViewModel x:Name="ViewModel"/>
</Page.DataContext>
<Grid>
<TextBlock Text="{x:Bind ViewModel.Text, Mode=OneWay}"/>
</Grid>
</Page>
```
If we build this and go to inspect the generated `MainPage.g.cs` file, we'll find a number of classes with various responsabilities - from updating individual UI controls to tracking the bindings, etc. In particular, we're interested in this one:
```csharp
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.19041.1")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
private class MainPage_obj1_BindingsTracking
{
private global::System.WeakReference<MainPage_obj1_Bindings> weakRefToBindingObj;
public MainPage_obj1_BindingsTracking(MainPage_obj1_Bindings obj)
{
weakRefToBindingObj = new global::System.WeakReference<MainPage_obj1_Bindings>(obj);
}
public MainPage_obj1_Bindings TryGetBindingObject()
{
return null; // Removed for brevity
}
public void ReleaseAllListeners()
{
// Removed for brevity
}
public void PropertyChanged_ViewModel(object sender, global::System.ComponentModel.PropertyChangedEventArgs e)
{
MainPage_obj1_Bindings bindings = TryGetBindingObject();
if (bindings != null)
{
string propName = e.PropertyName;
global::XBindSynchronizationContextSample.MainPageViewModel obj = sender as global::XBindSynchronizationContextSample.MainPageViewModel;
if (global::System.String.IsNullOrEmpty(propName))
{
if (obj != null)
{
bindings.Update_ViewModel_Text(obj.Text, DATA_CHANGED);
}
}
else
{
switch (propName)
{
case "Text":
{
if (obj != null)
{
bindings.Update_ViewModel_Text(obj.Text, DATA_CHANGED);
}
break;
}
default:
break;
}
}
}
}
private global::XBindSynchronizationContextSample.MainPageViewModel cache_ViewModel = null;
public void UpdateChildListeners_ViewModel(global::XBindSynchronizationContextSample.MainPageViewModel obj)
{
if (obj != cache_ViewModel)
{
if (cache_ViewModel != null)
{
((global::System.ComponentModel.INotifyPropertyChanged)cache_ViewModel).PropertyChanged -= PropertyChanged_ViewModel;
cache_ViewModel = null;
}
if (obj != null)
{
cache_ViewModel = obj;
((global::System.ComponentModel.INotifyPropertyChanged)obj).PropertyChanged += PropertyChanged_ViewModel;
}
}
}
}
```
This is the type that actually subscribes to the `PropertyChanged` event in our viewmodel and goes about updating the UI components. **This** is the only part that should need to care about the "UI thread", and this is the only part that should include the code to automatically deal with this for the user, both because it'd make all the rest of the code much simpler, and also because injecting the change here would be pretty efficient and with a small code change required.
In particular, the issue is when the `PropertyChanged_ViewModel` handler is invoked, since that could be done from an other thread if the `PropertyChanged` event was raised on another thread. To fix this, I propose the following:
```csharp
private global::System.WeakReference<MainPage_obj1_Bindings> weakRefToBindingObj;
private readonly DispatcherQueue dispatcherQueue;
public MainPage_obj1_BindingsTracking(MainPage_obj1_Bindings obj)
{
weakRefToBindingObj = new global::System.WeakReference<MainPage_obj1_Bindings>(obj);
dispatcherQueue = DispatcherQueue.GetForCurrentThread();
}
public void PropertyChanged_ViewModel(object obj, global::System.ComponentModel.PropertyChangedEventArgs e)
{
if (dispatcherQueue.HasThreadAccess)
{
PropertyChanged_ViewModel_OnDispatcherQueue(obj, e);
}
else
{
PropertyChanged_ViewModel_Dispatch(obj, e);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void PropertyChanged_ViewModel_Dispatch(Object obj, global::System.ComponentModel.PropertyChangedEventArgs e)
{
_ = dispatcherQueue.TryEnqueue(() => PropertyChanged_ViewModel_OnDispatcherQueue(obj, e));
}
private void PropertyChanged_ViewModel_OnDispatcherQueue(object sender, global::System.ComponentModel.PropertyChangedEventArgs e)
{
MainPage_obj1_Bindings bindings = TryGetBindingObject();
if (bindings != null)
{
string propName = e.PropertyName;
global::XBindSynchronizationContextSample.MainPageViewModel obj = sender as global::XBindSynchronizationContextSample.MainPageViewModel;
if (global::System.String.IsNullOrEmpty(propName))
{
if (obj != null)
{
bindings.Update_ViewModel_Text(obj.Text, DATA_CHANGED);
}
}
else
{
switch (propName)
{
case "Text":
{
if (obj != null)
{
bindings.Update_ViewModel_Text(obj.Text, DATA_CHANGED);
}
break;
}
default:
break;
}
}
}
}
```
Here's the git diff:
```diff
+using Windows.System;
+
namespace XBindSynchronizationContextSample
{
partial class MainPage :
@@ -170,11 +172,13 @@ namespace XBindSynchronizationContextSample
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
private class MainPage_obj1_BindingsTracking
{
+ private readonly DispatcherQueue dispatcherQueue;
public MainPage_obj1_BindingsTracking(MainPage_obj1_Bindings obj)
{
weakRefToBindingObj = new global::System.WeakReference<MainPage_obj1_Bindings>(obj);
+ dispatcherQueue = DispatcherQueue.GetForCurrentThread();
}
public MainPage_obj1_Bindings TryGetBindingObject()
@@ -198,6 +202,17 @@ namespace XBindSynchronizationContextSample
}
public void PropertyChanged_ViewModel(object sender, global::System.ComponentModel.PropertyChangedEventArgs e)
+ {
+ if (dispatcherQueue.HasThreadAccess)
+ {
+ PropertyChanged_ViewModel_OnDispatcherQueue(sender, e);
+ }
+ else
+ {
+ PropertyChanged_ViewModel_Dispatch(obj, e);
+ }
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private void PropertyChanged_ViewModel_Dispatch(Object obj, global::System.ComponentModel.PropertyChangedEventArgs e)
+ {
+ _ = dispatcherQueue.TryEnqueue(() => PropertyChanged_ViewModel_OnDispatcherQueue(obj, e));
+ }
+
+ public void PropertyChanged_ViewModel_OnDispatcherQueue(object sender, global::System.ComponentModel.PropertyChangedEventArgs e)
```
Now, this is just a proof of concept, but hopefully it illustrates the concept well enough 😄
## Rationale
<!-- Create a list that describes WHY the feature should be added to WinUI for all developers and users.
Proposals often have multiple motives for why we should do the work, so list each one as a separate bullet.
If applicable you can also describe how the proposal aligns to the current WinUI roadmap and priorities in a separate paragraph:
https://github.com/Microsoft/microsoft-ui-xaml/blob/master/docs/roadmap.md
-->
* Offer a new, modern and flexible handling of UI thread dispatching on WinUI
* Make working with multiple windows much easier and less error prone
* Greatly reduce the complexity on the backend side and increase the code modularity
* Address a major pain point in MVVM/similar that has been there for years, with a built-in solution
<!----------------------
The below sections are optional when submitting an idea or proposal.
All sections are required before we'll accept a PR to master, but aren't necessary to start the discussion.
------------------------>
## Scope
<!-- Please include a list of what the feature should and shouldn't do by filling in the table below.
'Must' implies that the feature should not ship without this capability.
'Should' is something we should push hard for, but is not absolutely required to ship.
'Could' is a nice-to-have; a good stretch goal that isn't painful if we don't achieve it.
'Won't' is a clear statement that the proposal/feature will intentionally not have that capability.
This list will evolve and grow as the proposal becomes more refined over time.
A good rule of thumb is to start your proposal with no more than 7 high-level requirements.
-->
| Capability | Priority |
| :---------- | :------- |
| Update the `x:Bind` codegen to handle the UI thread dispatch | Must |
| Update internal handlers to handle UI thread dispatch (eg. `CollectionChanged`) | Must |
| Introduce changes that would break existing codebases | Won't |
| Introduce overhead in current codebases or when the dispatch is not needed | Won't |