Christian Hubmann
Christian Hubmann

Reputation: 1512

Dialog with OK/Cancel behavior in C#/WPF with data binding

In my App class, I have a Collection of objects, like this: (the Collection is in the App class because I need to have access to it application-wide in different windows, etc.)

public partial class App : Application
{
    public ObservableCollection<Person> Persons { get; set; }

    public App()
    {
        Persons = new ObservableCollection<Person>();
        Persons.Add(new Person() { Name = "Tim", Age = 20 });
        Persons.Add(new Person() { Name = "Sarah", Age = 30 });
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

On the main window of the application, there is a ComboBox binding to the Persons Collection:

<ComboBox ItemsSource="{Binding Source={x:Static Application.Current}, Path=Persons}" DisplayMemberPath="Name"/>

Now I want to create a dialog, in which the user is able to add/remove/edit persons with the well known OK/Cancel button behavior. Can this be down easily? One important thing is that the items in the ComboBox must not be affected by the changes the user is making before pressing OK.

Thanks in advance!

Edit: I think I should point out that I don't want to edit a specific person in the dialog, but the whole list of persons.

Upvotes: 2

Views: 3472

Answers (1)

Robert Macnee
Robert Macnee

Reputation: 11840

Add and remove are simple enough since it will only happen when you click OK.

For editing, you more options:

  1. Make Person implement IClonable, pass in a cloned copy of the Person you are editing to be bound on the edit form, then switch out the appropriate Person in your Persons collection when you're done. This makes the edit form less complicated and more WPFey.

  2. Don't use binding on your edit form, just do a manual synch between the controls and the Person passed in when you're done. Least WPFey.

  3. A combination of 1 and 2 - the edit form has properties that mirror the properties of Person and are bound to its controls, then you synch the Person with the form's properties when you're done.

Upvotes: 3

Related Questions