开发者

How to retrieve data from a dialog box?

Just trying to figure out an easy way to either pass or share some data between the main window and a dialog box.

I've got a collection of variables in my main window that I want to pass to a dialog box so that they can be edited.

The way I've done it now, is I pass in the list to the constructor of the dialog box:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var window = new VariablesWindow(_templateVariables);
    window.Owner = this;
    window.Show开发者_如何学运维Dialog();
    if(window.DialogResult == true) 
        _templateVariables = new List<Variable>(window.Variables);
}

And then in there, I guess I need to deep-copy the list,

public partial class VariablesWindow : Window
{
    public ObservableCollection<Variable> Variables { get; set; }

    public VariablesWindow(IEnumerable<Variable> vars)
    {
        Variables = new ObservableCollection<Variable>(vars);
        // ...

So that when they're edited, it doesn't get reflected back in the main window until the user actually hits "Save".

Is that the correct approach? If so, is there an easy way to deep-copy an ObservableCollection? Because as it stands now, I think my Variables are being modified because it's only doing a shallow-copy.


I think you are indeed following the right approach here, but you need to make a deep copy of your ObservableCollection. To do so, make sure that your class 'Variable' is Clonable (try to implement ICloneable)

foreach(var item in vars)
{
    Variables.Add((Variable)item.Clone());
}


I would use events to communicate between the two forms if you want the main form to update while the dialog is open. Expose an event ("ItemAdded" or whatever) from your dialog class that the main form can handle. When that event is fired, update the main form as needed.


This extension method might help somebody:

public static IEnumerable<T> DeepCopy<T>(this IEnumerable<T> collection) where T : ICloneable
{
    return collection.Select(x => (T) x.Clone());
}

It simplifies my dialog window slightly:

public partial class VariablesWindow : Window
{
    public ObservableCollection<TemplateVariable> Variables { get; private set; }

    public VariablesWindow(IEnumerable<TemplateVariable> vars)
    {
        Variables = new ObservableCollection<TemplateVariable>(vars.DeepCopy());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜