我有两种形式“都开放”。我想从表单1(已经打开)向表单2(已经打开)发送一个datagridview单元格值。 (我不想在加载表单时传递文本,而是在已经打开的表单上进行一些编辑之后)。我已经在网上搜索了几天,但是找不到已经打开的表单。 (仅包含form.Show()
属性的文件。)
答案 0 :(得分:0)
您可以创建一个共享的单例类以保留您的数据
/// <summary>
/// A singleton class to keep your application data
/// </summary>
public class MySharedData
{
/// <summary>
/// Called when data changes
/// </summary>
public event EventHandler DataChanged;
private static MySharedData _instance;
private object _data;
public static MySharedData Instance => _instance ?? (_instance = new MySharedData());
private MySharedData()
{
}
/// <summary>
/// Gets or sets the data you want to share
/// </summary>
public object Data
{
get => _data;
set
{
_data = value;
OnDataChanged();
}
}
protected virtual void OnDataChanged()
{
DataChanged?.Invoke(this, EventArgs.Empty);
}
}
使用事件通知che数据已更新。
然后在表单中订阅该事件并添加您的更新逻辑
public class YourForm : Form
{
public YourForm()
{
MySharedData.Instance.DataChanged += Instance_DataChanged;
}
private void Instance_DataChanged(object sender, EventArgs e)
{
// TODO: redraw your form
}
}