我有一个Windows窗体。如果用户未选择复选框,则稍后按下一步时会打开一个新表单,但如果确实选中它,则使用相同的表单。
我希望当前表单的副本出现(具有相同的变量和控制值)(如果他们选中了该复选框),以便他们以后可以更改值而无需取消选中该复选框,然后再次按下一步,然后手动键入其他值。
Form duplicate = this;
只是引用相同的形式而没有这样的东西new(this)
。
我无法尝试,Form duplicate = new Form() = this
因为我的表单从早期的表单中获取了构造函数
。提前致谢
您可以在表单中添加以下方法:
public void RestoreState(Dictionary<string, object> controlStates,
Dictionary<string, object> membersStates)
{
InternalRestoreControls(controlStates);
InternalRestoreMembers(membersStates);
}
private void InternalRestoreControls(Dictionary<string, object> states)
{
foreach (var state in states)
{
Control c = this.Controls.Find(state.Key, true).FirstOrDefault();
if (c is TextBox)
{
(c as TextBox).Text = state.Value == null ? null : state.Value.ToString();
}
else if (c is CheckBox)
{
(c as CheckBox).Checked = Convert.ToBoolean(state.Value);
}
}
}
private void InternalRestoreMembers(Dictionary<string, object> membersStates)
{
// you might need to tweek this a little bit based on public/instance/static/private
// but this is not the point of your question
BindingFlags flags = BindingFlags.Instance | BindingFlags.Static
| BindingFlags.Public | BindingFlags.NonPublic;
var props = this.GetType().GetProperties(flags);
var fields = this.GetType().GetFields(flags);
foreach(var variable in membersStates)
{
var prop = props.FirstOrDefault(x => x.Name == variable.Key);
if(prop != null)
{
prop.SetValue(this, variable.Value);
continue;
}
var field = fields.FirstOrDefault(x => x.Name == variable.Key);
if(field != null)
{
field.SetValue(this, variable.Value);
continue;
}
}
}
private Dictionary<string, object> GetControlsState()
{
return new Dictionary<string, object>()
{
{ txtBox1.Name, txtBox1.Text },
// continue to the rest
};
}
private Dictionary<string, object> GetMembersState()
{
return new Dictionary<string, object>()
{
{ nameof(variable1), variable1 },
// continue to the rest
};
}
用法:
Form duplicate = new Form();
duplicate.RestoreState(this.GetControlsState(), this.GetMembersState());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句