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.
source to share
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.
source to share