I am trying to write an MVVM and WinUI3 based app. I have a ViewModel property, SelectedFolder, which is observable (using MVVM Toolkit). This is of type Folder which is a plain old class. Something like this:
public class ViewModel: ObservableRecipient {
private Folder selectedFolder;
public FolderModel SelectedFolder
{
get => selectedFolder;
set => SetProperty(ref selectedFolder, value, true);
}
}
public class FolderModel {
public string Name { get; set; }
}
Now in my XAML, I want to bind on ViewModel.SelectedFolder, and react to changes on it, but I want to show ViewModel.SelectedFolder.Name. So I am looking for something like this (which doesn't exist):
<TextBlock Text="{Binding ViewModel.SelectedFolder,Property=Name" />
How can I achive that? Things I thought about:
- Just make everything observable. This worked, but I am trying to avoid this, in order to decouple my model and my viewmodel. The reason is that my real model is a lot more complicated than this example, and I am trying to keep it close to what make sense for my "business logic", and to make my viewmodel cater to my view's needs.
- Make another "folder" class for my ViewModel's needs which has observable properties. I don't want to do this because it would duplicate a lot of code.
- Add an observable string property to my ViewModel: "SelectedFolderName".
- Abuse converters and write a GetNamePropertyConverter, which seems really silly.
SelectedFolderchanges, the newNameproperty value will be shown in the UI if you bind to it as{Binding ViewModel.SelectedFolder.Name}. You don't need to do anything else if you only want the data-bound value ofNameto change whenSelectedFolderis set to a new value.