devtunis devtunis - 1 year ago 46
C# Question

Many windows appears of click on Button ADD -MVVM WPF

I have Button ADD. When I click on it, I have a new window. I add the new Customer, my datagrid refreshes but just the first time!
Then every time I click on Button Add, I have a new window with the same information and so on... I get many windows ADD!

ViewModel:

private ObservableCollection<Custmor> _loadDataBinding;
public ObservableCollection<Custmor> loadDataBinding
{
get
{
return _loadDataBinding;
}
set
{
_loadDataBinding = value;
OnPropertyChanged("loadDataBinding");
}
}


public ViewModel1()
{
//Display my DataGrid
using (Test1Entities context = new Test1Entities())
{
_loadDataBinding = new ObservableCollection<Custmor>(context.Custmor.ToList());
}

//To Show the Window ADD from Window MainWindow
addCustomerMainWindow = new RelayCommand(add, canexecute);


CustomerToAddObject = new Custmor();


addCustomer1 = new RelayCommand(ADDFunction);
}



//To Show the Window ADD from Window MainWindow
private ICommand addCustomerMainWindow;
public ICommand AddCustomerMainWindow
{
get { return addCustomerMainWindow; }
}

private void add(object obj)
{
Add addView = new Add();
addView.DataContext = this;
addView.Show();
}

//The Button ADD from Window ADD
private ICommand addCustomer1;
public ICommand AddCustomer1
{
get { return addCustomer1; }
}

private void ADDFunction(object obj)
{
using (Test1Entities context = new Test1Entities())
{
context.Custmor.Add(customerToAddObject);
context.SaveChanges();
MessageBox.Show("Customer a été ajouté avec succès!");
}

_loadDataBinding.Add(CustomerToAddObject);
}



//textBox for window ADD: CustomerToAddObject.nom ;CustomerToAddObject.prenom and CustomerToAddObject.reference
private Custmor customerToAddObject;

public Custmor CustomerToAddObject
{
get { return customerToAddObject; }
set { customerToAddObject = value; }
}


How can I fix it for when I ADD a customer, the window ADD closes, and the Mainwindow still updates and so on? Clicking on the button ADD and it adds new customers, as many times as I want?

The result of my error:
enter image description here

Thanks for your help,

mm8 mm8
Answer Source

You could store a reference to the Add window and close it using this one. Something like this:

private Add addView;
private void add(object obj)

    if (addView != null)
        addView.Close();

    addView = new Add();
    addView.DataContext = this;
    addView.Show();
}

private void ADDFunction(object obj)
{
    using (Test1Entities context = new Test1Entities())
    {
        context.Custmor.Add(customerToAddObject);
        context.SaveChanges();
        MessageBox.Show("Customer a été ajouté avec succès!");
    }

    _loadDataBinding.Add(CustomerToAddObject);

    if (addView != null)
        addView.Close();
    CustomerToAddObject = new Custmor();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download