ViewModel initialization process in WPF + ReactiveProperty

1 minute read

** I don’t want to access the database or web service with the ViewModel constructor **

I don’t want to do heavy processing in the constructor. I don’t like exceptions. After getting the parameters with IntaractinNotification in the dialog, accessing the database and updating the model, or after the constructor is finished? That’s why.

View

Write a trigger that responds to the Loaded event in Interaction.Triggers.

<Window>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Loaded">
                <i:InvokeCommandAction Command="{Binding LoadedCommand}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>

</Window>

ViewModel

Write a command that responds to the Loaded event and perform database processing within the event processing.


public class FooViewModel : BindableBase
{
    private FooModel _model {get; set;}
    public ReactiveCommand LoadedCommand { get; set; } = new ReactiveCommand();
    public ReactiveProperty<string> Name {get; set;}
    public FooViewModel
    {
        //React to the event
        LoadedCommand.Subscribe(OnLoaded);
    }
    public void OnLoaded()
    {
        //Database processing here
        using(var db = new AppDbContext())
        {
            _model = db.Foos.FirstOrDefault();
        }
        Name = _model.ObserveProperty(x => x.Name).ToReactiveProperty();
        //New ReactiveProperty does not work without property change notification
        RaisePropertyChanged(null);
    }
}

Since Prism is used, BindableBase is used and RaisePropertyChanged is used for change notification.
If it is not Prism, use the implementation of INotifyPropertyChanged directly or use other methods.

Other

Using RaisePropertyChanged () (no arguments) instead of RaisePropertyChanged (null) does not update the View. Why.