I am still not sure if my approach is correct, but in an attempt to implement the MVVM pattern, I have created a model class 'Test' in the following way:
public class Test : BindableBase
{
private int testNumber;
public int TestNumber
{
get { return testNumber; }
set { SetProperty(ref testNumber, value) }
}
...
}
Then I created an instance of this class in my ViewModel
:
class ViewModel : BindableBase
{
private Test testVM;
public Test TestVM
{
get { return testVM; }
set { SetProperty(ref testVM, value); }
}
...
And in the XAML code of the View
I bind all the properties of the Test
class through the TestVM
property. Although this works fine, I ran into a problem when trying to implement a DelegateCommad
.
public DelegateCommand StartTestCommand { get; private set; }
So far, when implementing DelegateCommand
s, if I want to trigger the CanExecute
method when a property has changed, I include DelegateCommand.RaiseCanExecuteChanged()
inside the property's setter. Like so:
...
private bool duringTest;
public bool DuringTest
{
get { return duringTest; }
set
{
SetProperty(ref duringTest, value);
StartTestCommand.RaiseCanExecuteChanged();
}
}
...
This works fine for properties declared in the ViewModel
, but when using the same approach for the Test
properties, this no longer works.
...
private Test testVM;
public Test TestVM
{
get { return testVM; }
set
{
SetProperty(ref testVM, value);
StartTestCommand.RaiseCanExecuteChanged();
}
}
}
I would expect that every time a property from TestVM
was changed, the setter would be called, but instead the model is updated directly.
What am I doing wrong? What is the correct approach when using a Model
object in the ViewModel
?