MVVM Light and set data model field

3k views Asked by At

Here is the basic pattern of using MVVM Light's Set method:

public class MyViewModel : ViewModelBase
{
    private string _text;
    public Text 
    {
        get{ return _text; }
        set{ Set(()=>Text, ref _text, value); }
    }        
}

But in my project I keep fields in a DataModel class, which is nice for clone data and copy for cancel modifications:

public class MyDataModel
{
    public string Text;
}

public class MyViewModel : ViewModelBase
{
    private MyDataModel data;
    public Text 
    {
        get{ return data.Text; }
        set{ data.Text = value; RaisePropertyChanged(()=>Text); } 
    }        
}

But in this case I can't use the Set method, because its second parameter is ref and I can't use data.Text as a ref parameter.

Set( ()=>Text, ref data.Text, value ); // - its error

Any thoughts on how to solve this are welcome.

1

There are 1 answers

0
IngoB On

The code is invalid because "A property or indexer may not be passed as an out or ref parameter". You could override ViewModelBase and add another Set overload like so:

protected void Set<T>(Func<T> get, Action<T> set, T value, [CallerMemberName] string propertyName = null)
{
    T currentValue = get();

    if (EqualityComparer<T>.Default.Equals(currentValue, value))
        return;

    OnPropertyChanging(propertyName, currentValue);
    set(value);
    OnPropertyChanged(propertyName, value);
}

Then use:

public string Text
{
    get => data.Text;
    set => Set(() => data.Text, x => data.Text = x, value);
}