我在用户控件中有2个标签和一个属性: 这是财产:
private int _SelectIndex;
[Browsable(true)]
public int SelectIndex { get; set; }
和2个标签:
Label lbl1, lbl2;
void iControl()
{
lbl1 = new Label();
lbl2 = new Label();
lbl1.Name = "lbl1";
lbl2.Name = "lbl2";
lbl1.Click += lbl_Click;
lbl2.Click += lbl_Click;
this.Controls.Add(lbl1);
this.Controls.Add(lbl2);
}
点击:
void lbl_Click(object sender, EventArgs e)
{
Label selectedlbl = sender as Label;
if(selectedlbl.Name == "lbl1")
this.Select = 1;
else
this.Select = 2;
}
班级活动:
public class SelectEventArgs : EventArgs
{
private int index;
public SelectEventArgs(int index)
{
this.index = index;
}
public int ItemIndex
{
get
{
return index;
}
}
}
我控制中的自定义事件:
public event EventHandler SelectEvent;
protected virtual void OnSelectEvent()
{
if (SelectEvent!= null)
SelectEvent(this, new SelectEventArgs(this._SelectIndex));
}
我需要一个事件来获取和设置MainForm中的属性值,如下所示:
int index = 0;
public Form1()
{
InitializeComponent();
this.icontrol = new iControl();
this.SelectEvent += Select();
}
void Select(object sender, SelectItem e)
{
//use this to set value of Select
this.icontrol.SelectIndex = index;
//and this to get value of Select
index = this.icontrol.SelectIndex;
}
选择为空。 如何让它工作?
答案 0 :(得分:1)
代码有多个问题。请考虑以下提示来解决问题:
SelecetEvent
不属于Form
。该活动属于icontrol
。
this.SelectEvent += Select();
不正确,您应该使用:
icontrol.SelectEvent += Select;
如果您有自定义事件参数,则应以这种方式定义事件:
public event EventHandler<SelectEventArgs> SelectEvent;
您应该使用自己创建的OnSelectEvent
方法在属性的setter中引发事件。
要了解有关活动的更多信息,请查看C# Handling and Raising Events。
答案 1 :(得分:1)
我在这里张贴任何人都需要它:
1.Declare代表:
public delegate void SelectIndexEventHandler(object sender, SelectEventArgs e);
public class SelectEventArgs : EventArgs
{
private int index;
public SelectEventArgs(int index)
{
this.index = index;
}
public int ItemIndex
{
get { return index; }
set { index = value; }
}
}
2。声明一个事件SelectIndexChanged和一个方法OnSelectIndexChanged:
public event SelectIndexEventHandler SelectIndexChanged;
protected virtual void OnSelectIndexChanged(SelectEventArgs e)
{
if (SelectIndexChanged != null)
SelectIndexChanged(this, e);
}
3.在setter中打电话:
public int SelectIndex
{
get { return _SelectIndex; }
set {
_SelectIndex = value;
OnSelectIndexChanged(new SelectEventArgs(value));
}
}
然后是MainForm:
this.gListBox1.SelectIndexChanged += icontrol_SelectIndexChanged;
void icontrol_SelectIndexChanged(object sender, SelectEventArgs e)
{
var current = e.ItemIndex;
}
再次感谢jbmintjb Reza Aghaei。
答案 2 :(得分:0)
查看列表框控件上的SelectedIndexChanged事件,认为这就是您要找的内容