Hello @Omar Mohamed !
In WinUI 3, Window itself doesn’t have a DataContext property like WPF does, so you have to set it on the root element of your XAML tree (or use x:Bind which doesn’t require a DataContext at all).
Here’s way to share one view model instance across multiple pages and user controls that you can try
Create your shared ViewModel
Make it implement INotifyPropertyChanged so bindings update automatically.
public class AppViewModel : INotifyPropertyChanged
{
private string _firstProp;
public string FirstProp
{
get => _firstProp;
set { _firstProp = value; OnPropertyChanged(); }
}
private string _secondProp;
public string SecondProp
{
get => _secondProp;
set { _secondProp = value; OnPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
Instantiate it once and make it accessible
You can store it in App.xaml.cs so all pages can reuse the same instance.
public partial class App : Application
{
public static AppViewModel SharedViewModel { get; } = new AppViewModel();
protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
m_window = new MainWindow();
m_window.Activate();
}
private Window m_window;
}
Set the DataContext in your Window/Page/UserControl
In your MainWindow.xaml
<Window
x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyApp">
<Grid x:Name="RootGrid">
<Frame x:Name="MainFrame"/>
</Grid>
</Window>
In your MainWindow.xaml.cs
public sealed partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
RootGrid.DataContext = App.SharedViewModel; // Set on root element
MainFrame.Navigate(typeof(Page1));
}
}
In each Page you can either:
- Inherit the
DataContextfrom the Frame (if you don’t override it), or - Explicitly set it in the page’s constructor.
public sealed partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
DataContext = App.SharedViewModel; // Optional if inherited
}
}
For UserControl, similar approach to set DataContext for shared instance, or bind it from the parent.
Example XAML binding
<TextBlock Text="{Binding FirstProp, Mode=TwoWay}"/>
<TextBox Text="{Binding SecondProp, Mode=TwoWay}"/>
By using one shared ViewModel as the DataContext for all pages and controls, you get consistent, synchronized data updates across your entire WinUI 3 app without duplicating state or wiring up extra events.
I hope this helps! Let me know if you have any questions, if you find my answer is useful, feel free to mark this as final answer!