C # implementation of EditableValue <T>

I'm looking for a ready-to-use implementation of a common problem - to get property information like: changed, initial value, etc.

I'm sure I've seen something like this already, but I couldn't find it.

I am thinking of something like this:

public EditableValue<string> Name;

      

and then using:

if(Name.HasChanged)
{
    if(string.IsNullOrEmpty(Name.NewValue))
        Name.DiscardChanged();
}

      

Do you know any solutions for this?

I am creating a WPF and MVVM based project.

+3


source to share


2 answers


I once had a similar need and wrote a class that looks like this:

public class EditableValue<T> : BindableBase where T : struct
{
    private T _value;
    private T? _displayValue;

    public T Value
    {
        get { return _value; }
        set
        {
            _value = value;
            OnPropertyChanged(() => Value);
        }
    }

    public T DisplayValue
    {
        get { return _displayValue ?? Value; }
        set
        {
            _displayValue = value;
            OnPropertyChanged(() => DisplayValue);
        }
    }

    public bool HasChanges
    {
        get { return _displayValue.HasValue; }
    }

    public void DiscardChanges()
    {
        _displayValue = null;
        OnPropertyChanged(() => DisplayValue);
    }

    public void ApplyChanges()
    {
        Value = DisplayValue;
        OnPropertyChanged(() => DisplayValue);
        OnPropertyChanged(() => Value);
    }
}

      



Note that it uses BindableBase from the Prism.Mvvm nuget package to implement INotifyPropertyChanged

.

Binding with only DisplayValue

gives you the ability to change values ​​in the UI and by hitting save (or discard) you can set Value

(or reset DisplayValue

). While nothing is set for _displayValue

, the actual value will be transmitted. You can also bind to Value

if you are only interested in the actual value with no prominent changes.

0


source


I suggest you try to implement INotifyPropertyChanged

in your class EditableValue

and then listen for the property changed event.



If you try to share your code then we can fix any issues that may arise.

0


source







All Articles