views:

85

answers:

1

How can i have a dialog for editing the properties of a class with binding, and have OK-Cancel in the dialog?

My first idea was this:

public partial class EditServerDialog : Window {
    private NewsServer _newsServer;

    public EditServerDialog(NewsServer newsServer) {
        InitializeComponent();

        this.DataContext = (_newsServer = newsServer).Clone();
    }

    private void ButtonClick(object sender, RoutedEventArgs e)
    {
        switch (((Button)e.OriginalSource).Content.ToString()) {
            case "OK":
                _newsServer = (NewsServer)this.DataContext;
                this.Close();
                break;
            case "Cancel":
                this.Close();
                break;
        }
    }
}

When in the switch, case "OK", the DataContext contains the correct information, but the originally passed NewsServer instance does not change.

A: 

The original instance of your NewsServer is not changed because you haven't actually modified it. After you constructor is called you have the following three NewsServer references:

newsServer = original instance
_newsServer = original instance
DataConext = clone of original instance

After the OK button is clicked the references will be as follows:

newsServer = original instance
_newsServer = clone of original instance (possibly modified)
DataConext = clone of original instance (possibly modified)

Remember that objects are reference types, in your assignment to _newsServer you are only updating its reference, not the value of the object itself.

In order to allow updating the NewsSource object itself there are two options that come to mind, other options likely exist, the first is probably the simplest.

  • Implement an Update(NewsSource source) method on your NewsSource object then instead of performing the new assignment to the _newsServer field instead call the update method on it and pass in the DataContext
  • Add an event to your dialog that is raised when an update occurs, then in your handler assign the value of _newsServer to whatever object you initially passed into the dialog; this would require exposing the _newsServer with public/internal property.
Richard C. McGuire
How should i do this and still be able to cancel and/or apply?
Erik