开发人员技术 | Windows 窗体
一组用于开发图形用户界面的 .NET Framework 托管库。
我已将我的类的实例存储在剪贴板中,并且从剪贴板中检索相同的实例时,始终为空。我标记了我的类 [Serializable],但仍然没有运气。我无法找出我在哪里犯了错误。这是我的代码。请看一下并告诉我我在哪里犯了错误以及要在代码中更改什么,因此我应该能够检索我存储在剪贴板中的对象。
//Save object to clipboard
private void BtnSet_Click(object sender, EventArgs e)
{
NodeCollection ndCollection = new NodeCollection();
TunerDetails tds = null;
selectednode = tvCsmTuner.SelectedNode;
if (selectednode == null) return;
if (selectednode != null)
{
ndCollection.Name = selectednode.Text;
ndCollection.Text = selectednode.Text;
ndCollection.Tag = selectednode.Tag;
foreach (TreeNode node in selectednode.Nodes)
{
ndCollection.Nodes.Add(new NodeCollection { Name = node.Text, Text = node.Text, Tag = node.Tag });
}
DataObject data = new DataObject();
data.SetData(ndCollection);
Clipboard.SetDataObject(data);
}
RemoveNode();
}
//Read object back from clipboard
private void BtnGet_Click(object sender, EventArgs e)
{
DataObject retrievedData = (DataObject)Clipboard.GetDataObject();
if (retrievedData.GetDataPresent(typeof(NodeCollection)))
{
NodeCollection ndCollection1 = retrievedData.GetData(typeof(NodeCollection)) as NodeCollection;
if (ndCollection1 != null)
{
MessageBox.Show(ndCollection1.Name);
}
}
}
[Serializable]
public class NodeCollection
{
public NodeCollection() {
Nodes = new List<NodeCollection>();
}
#region PROPERTIES
public string Name { get; set; }
public string Text { get; set; }
public object Tag { get; set; }
public List<NodeCollection> Nodes { get; set; }
#endregion
}
下面的代码在单独的winform项目中工作正常,但是当我在实际项目中复制相同的代码时,此行返回NULL return retrievedData.GetData(typeof(NodeCollection))作为NodeCollection;
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var expected = new NodeCollection();
expected.Name = "Root";
expected.Text = "Root";
expected.Tag = new object();
for (int x = 0; x <= 1; x++)
{
expected.Nodes.Add(new NodeCollection() { Name = "Child 1", Text = "Child 1", Tag = new object() });
}
SetClipboardData(expected);
}
private void button2_Click(object sender, EventArgs e)
{
var actual = GetClipboardData();
}
private void SetClipboardData(NodeCollection nodeCollection)
{
var data = new DataObject();
data.SetData(nodeCollection);
Clipboard.SetDataObject(data);
}
//Read object back from clipboard
private NodeCollection GetClipboardData()
{
NodeCollection nd = null;
var retrievedData = Clipboard.GetDataObject();
if (retrievedData.GetDataPresent(typeof(NodeCollection)))
nd= retrievedData.GetData(typeof(NodeCollection)) as NodeCollection;
return nd;
}
}
[Serializable]
public class NodeCollection
{
public NodeCollection()
{
Nodes = new List<NodeCollection>();
}
#region PROPERTIES
public string Name { get; set; }
public string Text { get; set; }
public object Tag { get; set; }
public List<NodeCollection> Nodes { get; set; }
#endregion
}
请帮助我我错过了什么。谢谢
Note:此问题总结整理于: Winform: Always getting NULL when retrieve data from clipboard