DataBinding是否将对象参数更改为ByRev?

时间:2014-01-22 13:39:09

标签: c# wpf data-binding dictionary listbox

您好我正在尝试数据绑定,并且在这里发生了一些奇怪的事情。我有一个MainWindow和一个VarAssignmentWindow。我还有一个存储我的数据的词典:

public Dictionary<String, MDevice> devices = new Dictionary<string,MDevice>();

VarAssignmentWindow我想更改devices - 对象内部的某些值,如果我单击确定按钮,或者如果我点击取消按钮则不应用更改。

我用这种方式调用VarAssignmentWindow

        VarAssignmentWindow window = new VarAssignmentWindow(devices);
        window.Owner = this;
        window.ShowDialog();

        if (window.canceled == false)
        {
            //Save changes if OK was clicked
            devices = window.devices;
        }

正如您所看到的,如果我点击确定按钮,我想用MainWindow.devices覆盖VarAssignmentWindow.devices,否则应该不会发生。

现在这里是VarAssignmentWindow类内部的内容:

    public Dictionary<String, MDevice> devices = new Dictionary<string,MDevice>();
    public bool canceled = true;

    public VarAssignmentWindow(Dictionary<String, MDevice> devices)
    {
        InitializeComponent();
        this.devices = devices; //This seems to be ByRef, but only, if i bind the items to the listbox
        updateListBox();
    }

    private void updateListBox()
    {
        lstVars.Items.Clear();
        foreach (var dev in devices)
        {
            foreach (var vari in dev.Value.savedVarDic)
            {
                lstVars.Items.Add(vari.Value);
            }
        }
    }

    private void cmdOK_Click(object sender, RoutedEventArgs e)
    {
        canceled = false;
        this.Close();
    }

    private void cmdCancel_Click(object sender, RoutedEventArgs e)
    {
        canceled = true;
        this.Close();
    }

如果我更改了ListBox中的任何内容,那么无论是否点击取消或确定,它总是在 MainWindow.devices 对象中更改。

确定ByRef是否进行了以下测试:

    public VarAssignmentWindow(Dictionary<String, MDevice> devices)
    {
        InitializeComponent();
        this.devices = devices;
        updateListBox();
        this.devices = null;
    }
    --> devices in MainWindow is null afterwards

    public VarAssignmentWindow(Dictionary<String, MDevice> devices)
    {
        InitializeComponent();
        this.devices = devices;
        //updateListBox();
        this.devices = null;
    }
    --> devices in MainWindow is not null (its what it was before)

这只是我犯的一个愚蠢的DataBinding错误吗?请帮忙!

1 个答案:

答案 0 :(得分:2)

不,数据绑定不会将对象参数更改为ByRef。 正在编辑devices控件中的相同 MainWindow集合。在传递给您的VarAssignmentWindow Window之前制作该集合的深层副本。这样,如果用户想要取消,您只需返回原始集合,如果保存,则返回新的已编辑集合。