如何从对话框中检索数据? [英] 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.ShowDialog();
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".
这是正确的方法吗?如果是这样,是否有一种简单的方法来深度复制 ObservableCollection?因为就目前而言,我认为我的变量正在被修改,因为它只是做一个浅拷贝.
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.
推荐答案
我认为您在这里确实遵循了正确的方法,但您需要制作 ObservableCollection 的深层副本.为此,请确保您的类变量"是可克隆的(尝试实现 ICloneable)
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());
}
这篇关于如何从对话框中检索数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!