This is for a MVVM based WPF project:
I am using an ExpandoObject
in a view model for a dialog, which works very nicely since it implements INotifyPropertyChanged
and I can bind to properties of the object directly in XAML.
However, to account for the user manipuating data but then hitting cancel I need to make a copy of the ExpandoObject
to restore the original content.
In the dialog no properties are added to the object.
How can I clone it?
For ExpandoObject, you can simply check whether the property is defined as a key in the underlying dictionary. For other implementations, it might be challenging and sometimes the only way is to work with exceptions.
// Add properties dynamically to expando AddProperty(expando, "Language", "English"); The AddProperty method takes advantage of the support that ExpandoObject has for IDictionary<string, object> and allows us to add properties using values we determine at runtime.
The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject. sampleMember instead of more complex syntax like sampleObject.
Shallow copy:
static ExpandoObject ShallowCopy(ExpandoObject original)
{
var clone = new ExpandoObject();
var _original = (IDictionary<string, object>)original;
var _clone = (IDictionary<string, object>)clone;
foreach (var kvp in _original)
_clone.Add(kvp);
return clone;
}
Deep copy:
static ExpandoObject DeepCopy(ExpandoObject original)
{
var clone = new ExpandoObject();
var _original = (IDictionary<string, object>)original;
var _clone = (IDictionary<string, object>)clone;
foreach (var kvp in _original)
_clone.Add(kvp.Key, kvp.Value is ExpandoObject ? DeepCopy((ExpandoObject)kvp.Value) : kvp.Value);
return clone;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With