嗨,我正在試驗數據綁定,並在這裏發生了一些奇怪的事情。我有一個MainWindow
和一個VarAssignmentWindow
。我也有我的地方數據存儲在詞典:DataBinding是否將對象參數更改爲ByRev?
public Dictionary<String, MDevice> devices = new Dictionary<string,MDevice>();
在VarAssignmentWindow
我想改變devices
-object內的一些值,如果我上的OK按鈕點擊,或者如果我打不應用更改取消按鈕。
我叫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
如果我打的OK按鈕,otherwhise絕不應發生。
現在這裏是什麼的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();
}
如果我改變列表框裏面任何東西,它總是在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)
難道僅僅是一個愚蠢的錯誤的數據綁定我做?請幫忙!
你說我編輯_same_設備,當我裏面'VarAssignmentWindow' this.devices改變,所以this.devices只是一個指針'MainWindow.devices'?而且這不是ByRef?或者你的意思是數據綁定不會改變,因爲這種參數總是ByRef呢? – Stefan
您的第二句話......無論如何,所有對象都通過引用傳遞。你在這裏傳遞實際的對象:'new VarAssignmentWindow(devices);'。而不是這樣,嘗試更多像這樣的:'new VarAssignmentWindow(copyOfDevices);'。顯然,*你*必須創建'copyOfDevices'克隆。 – Sheridan
我用[亞歷Burtsev的](http://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically)deepcopy的解決方案,它的工作原理很好,謝謝你填補我的知識空白(我認爲對象總是ByRef,但我的第二個實驗愚弄了我一下(最後一塊代碼)),我仍然不知道爲什麼設備在最後的主窗口類中不爲空示例 – Stefan