如何在c#中重置用户控件's控件到初始状态
本文关键字:控件 初始状态 用户 | 更新日期: 2023-09-27 18:01:41
在我的应用程序中,我有一个用户控制,当我点击我的应用程序的添加按钮。它应该为用户控件创建一个对象,并且创建的用户控件副本应该添加到面板控件中。我做了这一切……但我的问题是随着添加按钮。我有一个重置按钮。当我点击这个按钮时,它应该重置所有添加到面板的用户控件,我怎么能做到这一点。有人知道吗?请帮帮我
我的重置码是
foreach (Control x in bodyPanel.Controls)
{
if (x is TimerUserControl)
{
obj_TimerUserControl.ResetControl();
}
}
当我执行这个时,最后创建的对象只被重置。其余的都照常运行。Resetcontrol()是一个在TimerUserControl中声明的方法。
实现目标的最简单方法似乎是创建一个带有"ResetControl"作为方法的接口。让你所有的控件实现这个接口,而不是检查控件的类型是否为"TimerUserControl",你要检查类型是否为你的接口。
public interface IResetable
{
void ResetControl();
}
…
foreach(var control in bodyPanel.Controls)
{
var resetable = control as IResetable;
if (resetable != null)
resetable.ResetControl();
}
你的问题不太清楚,但我试着描述我所理解的,据我所知,有两种可能性
概率- 1:你有一个叫做"User Control"的类,当这个类被实例化(创建了这个对象的一个新实例——在。Net框架中所有的都是对象),并且被实例化的对象初始化/实现自己为父对象。
当用户/开发人员需要添加到父对象后,实例化对象可以通过一些过滤器选项(即通过索引no)将其初始值设置为默认值
概率-2:父对象删除所有添加的元素
这两个概率可以用同样的方法求解。
下面是一些示例代码:
//This is sample parent object
public class Container : Panel
{
// In your situation this list is your controls
public List<NumBox> Elements { get; set; }
public Container()
{
}
public Container( List<NumBox> numericBoxList )
{
this.Elements.AddRange( numericBoxList ) ;
}
public void Add ( NumBox numericBoxInstance )
{
// we check that elements has our numbox instance or not..
// if our instance is not in the elements then find method returns null
if (this.Elements.Find( numericBoxInstance ) == null)
{
this.Elements.Add ( numericBoxInstance )
}
public void DeleteElement ( NumBox numboxInstance )
{
this.Elements.Remove (numboxInstance );
}
public void DeleteAllElements ()
{
this.Elements = null;
// The IENumerable objects such as Lists can be easily set the object to the
// "initialization moment" - something like just create a new and empty object -
// with assigning to "null"..CSharp compiler as clever as understand that you want clear all
}
public void UpdateElement (int indexNo, NumBox updatedNumBox)
{
this.Elements[indexNo] = updatedNumBox;
}
// And The Sample Child object
public class NumBox : TextBox
{
public NumBox()
{
}
public NumBox ( int value )
{
this.Text = value.ToString();
}
//overloads for other numeric options such as short, long, decimal, float etc.
public void Reset()
{
this.Text = null;
}
// Some Other Useful Methods that you need in the project
}
和示例用法:
int i = 12345;
var box = new NumBox (i);
var parent = new Container();
parent.Add( box );
var j = parent.Elements.FindIndex ( box );
// FindIndex is a built-in IENumerable method like Find() or others that you can see in Intellisense
if (j > = 0)
{
parent.Elements[j].Reset();
}
var box1 = new NumBox(987654);
parent.UpdateElement(j, box1);
parent.DeleteAllElements();
在reset button handler下写下面的代码,它会解决这个问题
foreach (Control ctrl in bodyPanel.Controls)
{
if (ctrl.GetType().Name == "TimerUserControl")
{
TimerUserControl obj = ctrl as TimerUserControl;
obj.ResetControl();
}
}