MVVM Light and set data model field
Asked Answered
B

1

6

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.

Bondy answered 16/6, 2015 at 20:5 Comment(3)
What's the problem? Is the second code example not equivalent to the first?Woothen
Yes it's equivalent , but i want to minimize codeBondy
The Set method is just one of several ways to raise property changed notifications with MVVMLight. Your second example is perfectly valid (although Set() does perform a equality comparison before raising the notification event).Ailsun
J
0

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);
}
Jugate answered 15/8, 2020 at 5:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.