Return from Dialog
Returning from the Dialog
Now that the user can select one of our Albums, we need to be able to close the Dialog and return the result to the ViewModel
that called the dialog.
Notice that our MusicStoreViewModel
has a SelectedAlbum
property that we added previously and that the ListBox
on the MusicStoreView
has its SelectedItem
property bound to this SelectedAlbum
property of the view model.
This means that when the user clicks to select an album, the listbox shows that it is selected by highlighting the item.
At the same time the SelectedAlbum
property will be kept in sync and set to the AlbumViewModel
instance that represents the SelectedItem
of the ListBox
.
The Button
of the MusicStoreView
has its Command
property bound to BuyMusicCommand
. This doesn't exist yet so lets add this to MusicStoreViewModel
with the following code.
public ReactiveCommand<Unit, AlbumViewModel?> BuyMusicCommand { get; }
Note we are using ReactiveCommand
this is where we are using ReactiveUI to provide some of the plumbing for us. Avalonia expects commands to be of type ICommand
and ReactiveCommand
implements this interface.
Note that ReactiveCommand<TParam, TResult>
has some type arguments. Commands can take a parameter, however we do not need a parameter in this case, so we use Unit
which is kind of a dummy type, it contains no data. Reactive Commands can also return a result. This will be useful for returning the Album the user wants to buy.
Now add the following lines to the constructor of MusicStoreViewModel
in order to instantiate the command and implement the code needed to return a result from the dialog:
BuyMusicCommand = ReactiveCommand.Create(() =>
{
return SelectedAlbum;
});