简体   繁体   中英

Prevent ValueChanged execution while ViewModel is being initialized

i want to prevent ValueChanged event execution while I'm initializing form with data.

I have 2 form constructors (Wpf Window). The problem is with the second one, used for entry update.

This is xaml.cs code:

public MyForm() // for new entry
{
    InitializeComponent();
    DataContext = MyViewModel;
}

public MyForm(int id) // for entry update - PROBLEM!
{
    InitializeComponent();
    DataContext = MyViewModel;

    MyViewModel.PreapareFormWithData(id); // load data
}

private void dteDate_EditValueChanged(object sender, DevExpress.Xpf.Editors.EditValueChangedEventArgs e)
{
    if (!MyViewModel.IsInitializing) // PROBLEM!
        MyViewModel.DateChanged();
}

After I create a new instance of MyForm, and call ShowDialog(), the event dteDate_EditValueChanged is being fired (because MyModel.Date is being set from database, not because user changed value on GUI control).

I tried to avoid this, by setting the IsInitializing flag to false, but the problem is that the PreapareFormWithData() method if already executed (and the flag is set to false) when ValueChanged is fired.

My current solution is to change IsInitialized flag with ValueChangedCounter, so I can put ValueChangedCounter > 1 instead od !IsInitialized, but I'm not really happy with that kind of solution.

Here is my ViewModel.cs

private MyViewModel _MyViewModel;

public MyViewModel MyViewModel 
{
    get
    {
        if (_MyViewModel== null)
            _MyViewModel = new MyViewModel();
        return _MyViewModel;
    }
    set { _MyViewModel= value; OnPropertyChanged("MyViewModel"); }
}

public bool IsInitializing = true; // flag

public MyViewModel() { }

public void PreapareFormWithData(int id)
{
    MyModel = MyModel.GetData(id);
    IsInitializing = false; // data loading completed, set flag to false
}

public void DateChanged()
{
    // MyModel.Date changed, do some stuff...
}

And My Model:

public class MyModel
{
    public DateTime Date { get; set; } // without OnPropertyChanged()...
}

Replace

if (!MyViewModel.IsInitializing) // PROBLEM!
    MyViewModel.DateChanged();

with

if (!IsLoaded) return;

MyViewModel.DateChanged();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM