我有一组面板,当用户点击它们时会突出显示。我想强迫它们表现为一组单选按钮,因此只有点击的单选按钮才会突出显示,而其他按钮则不会。
我想必须有一种方法可以从内部操纵整个集合(set property to false),因为事件是由集合中的一个项触发的。有一种方法可以让一个项目操纵整个集合吗?这是应用程序中的一个常见功能,所以我想必须有一个模式如何正确地执行它。感谢。
答案 0 :(得分:0)
您可以存储面板的集合并处理所需的功能,如以下代码段所示:
List<Panel> Panels;
private void Initialization()
{
Panels = new List<Panel>();
Panels.Add(pnl1);
Panels.Add(pnl2);
//add all your panels into collection
foreach(Panel Item in this.Panels)
{
//add handle to panel on click event
Item.Click += OnPanelClick;
}
}
private void OnPanelClick(object sender, EventArgs e)
{
foreach(Panel Item in this.Panels)
{
//remove highlight from your panels, real property should have other name than Panel.HighlightEnabled
Item.HighlightEnabled = false;
}
((Panel)sender).HighlightEnabled = true; //add highlight to Panel which invoked Click event
Application.DoEvents(); //ensure that graphics redraw is completed immediately
}
private void AddNewPanelIntoLocalCollection(Panel panel)
{
//here you can add new items to collection during program lifecycle
panel.Click += OnPanelClick;
this.Panels.Add(panel);
}
答案 1 :(得分:0)
我就是这样做的
public class SelectOne : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
private bool isSelected = false;
private HashSet<SelectOne> selecteOnes = null;
public bool IsSelected
{
get { return isSelected; }
set
{
if (isSelected == value) return;
if (isSelected && selecteOnes != null)
{
foreach (SelectOne so in selecteOnes)
{
if (so == this) continue;
so.IsSelected = false;
}
}
NotifyPropertyChanged("IsSelected");
}
}
public SelectOne() { }
public SelectOne(bool IsSelected) { isSelected = IsSelected; }
public SelectedOne(bool IsSelected, HashSet<SelectOne> SelecteOnes)
{
isSelected = IsSelected;
selecteOnes = SelecteOnes;
}
}
答案 2 :(得分:0)
最终我确实找到了一种方法,只需一名代表就可以做到这一点。
在A组中,我有一组对象B
List<B> b = new List<B>
B类,需要具有Id met参数
的void metod的唯一ID和delegetedelegate void DeleteItemDelegate(int id);
class B
{
public int ID {get; set;}
public DeleteItemDeleate deleteThis {set; get;}
}
A类有这样的方法:
public void RemoveItem(int id)
{
for (int x = 0; x < b.Count; x++)
{
if (b[x].id == id)
{
b.RemoveAt(x);
}
}
}
将新B对象添加到List中时,只需将metod RemoveItem添加到B.deleteThis委托
B bObject = new B();
bObject.deleteThis = RemoveItem;
b.Add(bObject);
现在您需要做的就是在B类中添加DeleteMe metod
void DeleteMe()
{
// and call local delegate - pointing to metod which actually can manipulate the collection
deleteThis(id);
}