0

Imagine that I have a textbox that bind to a value retrieved from database. And I have a cancel button.Something like below:

<TextBox Text="{Binding [someViewModel].TestVar, Mode=TwoWay}"></TextBox>

Now says TestVar's value is 10 and when user updated the value and press the cancel button, I will show a popup to tell user that your data will be lost. Are you sure you want to proceed?

My idea is using either TextChanged or UpdateSourceTrigger="PropertyChanged" to update a boolean flag and upon cancel button onclick do the checking. But the thing is if user updated the value first from 10 to 5, then back to 10? Then when user press the cancel button, there should be no alert message.

May I know what would be the most efficient way to achieve the objective?

SuicideSheep
  • 5,260
  • 19
  • 64
  • 117

3 Answers3

1

There are multiple ways to achieve this.

  1. Make a deep clone of your viewmodel and validate two integer values. See How do you do a deep copy an object in .Net

  2. Make a IntegerViewModel with two fields

    // the value
    public int Value { get; set; }
    // the temporary backup value on edit.
    public int BackupValue { get; set; }
    
Community
  • 1
  • 1
csteinmueller
  • 2,427
  • 1
  • 21
  • 32
  • Wont it be heavy to store a copy of it just for a validation purpose? – SuicideSheep Feb 17 '14 at 09:01
  • 2
    If you want to avoid informessages after the value changes but has the old value again you have to know the old value. You can only know the old value if you save it. So you have to make a copy in any way. If it is just this one value I won't make a copy of viewmodels or extra viewmodels for primitive types. Then just store it in your viewmodel. – csteinmueller Feb 17 '14 at 09:05
1

In MVVM scenario implement IEditableObject interface in View-model as explained and recommend in this SO Answer

IEditableObject is a good interface anytime you want to be able to roll back changes.

Community
  • 1
  • 1
Mujahid Daud Khan
  • 1,983
  • 1
  • 14
  • 23
0

If You want only to know that the changes were perfomed, not exactly which property value changed into another etc. You can strore this information in a simple boolean flag like that:

private bool hasUnsavedChanges;

private string somePropertyValue;
public string SomeProperty
{
    get
    {
        return this.somePropertyValue;
    }

    set
    {
        if(this.somePropertyValue!= value)
        {
            this.hasUnsavedChanges = true;
        }

        this.somePropertyValue= value
    }
}

If You need to know everything about changes make a copying constructor of Your transfer object and store it in some backupCopy field. In validation method You just compare all required Properties of existing object and it's backup

Koscik
  • 190
  • 1
  • 3
  • 14