I have a WinUI3 app that I am trying to use in an MVVM pattern.
I have a ViewModel that implements INotifyPropertyChanged. In that ViewModel I have a simple string property (TextBoxContent) that calls the OnPropertyChanged() when the value changes.
public class SimpleVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string? name = null)
{
if (name is not null)
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private string _textBoxContent = "Hello from SimpleVM";
public string TextBoxContent
{
get => _textBoxContent;
set
{
if (_textBoxContent != value)
{
_textBoxContent = value;
OnPropertyChanged();
}
}
}
}
In my MainWindow.xaml I have a Grid that I have named RootGrid and within that a TextBox where Text={Binding TextBoxContent...}.
<Grid x:Name="RootGrid">
<TextBlock
Text="{Binding TextBoxContent, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
In my MainWindow.xaml.cs code behind I assign an instance of ViewModel to RootGrid.DataContext late in the constructor, well after InitializeComponent().
RootGrid.DataContext = vm;
This is very much the pattern I use in WPF. In Visual Studio, this compiles without errors, loads and binds the property in the ViewModel to the TextBox perfectly.
However, if I then package the app into an appbundle and install the app on my computer, I can identify that an exception occurs when the ViewModel is assigned to the RootGrid.DataContext (that error is Object Reference not set...). If I then remove the :INotifyPropertyChanged implementation to the ViewModel, an exception does not occur when I assign the ViewModel instance to RootGrid.DataContext but then the value of TextBoxContent in the vm never is bound to TextBox in the xaml
I know I can do this all with x:Bind and bypass using the DataContext altogether. However, how can I get a ViewModel:INotifyPropertyChanged to assign to a DataContext without causing an exception? Or, in WinUI, that was never the intention for binding in the first place?