C# 如何找出我按了哪个按钮?
想象一下Facebook上的通知下拉菜单。 我想实现类似的东西。单击“Slet”时,应该从列表中删除该通知。 然后创建此方法:C# 如何找出我按了哪个按钮?,c#,wpf,stackpanel,icommand,relaycommand,C#,Wpf,Stackpanel,Icommand,Relaycommand,想象一下Facebook上的通知下拉菜单。 我想实现类似的东西。单击“Slet”时,应该从列表中删除该通知。 然后创建此方法: private void DeleteNotification() { Notifications.Remove(NotificationForDeletion); AddNotificationsToPanel(Notifications, Panel); } 问题是我们不知道要删除哪个通知,因为我不知道如何查看单击了哪个按钮。有什么想法吗?您应该
private void DeleteNotification()
{
Notifications.Remove(NotificationForDeletion);
AddNotificationsToPanel(Notifications, Panel);
}
问题是我们不知道要删除哪个通知,因为我不知道如何查看单击了哪个按钮。有什么想法吗?您应该通过为按钮分配每个通知的唯一标识符来使用该按钮的属性。我假设您的通知具有唯一的整数id:
//Add a delete button:
var del = new Button();
del.Content = "Slet";
del.FontSize = 24;
del.Command = DeleteNotificationCommand;
del.CommandParameter = notification.Id; // <-- unique id
horizontalStackPanel.Children.Add(del);
//添加删除按钮:
var del=新按钮();
del.Content=“Slet”;
del.FontSize=24;
del.Command=DeleteNotificationCommand;
del.CommandParameter=notification.Id;//我的通知类中没有标识符,但现在有了!实际上,它只需编写以下代码即可工作:返回新的RelayCommand(DeleteNotification);但是谢谢你的帮助!不客气,是的,我想这也行,我更新了答案。我编辑了你的标题。请参阅“”,其中的共识是“不,他们不应该”。
private void DeleteNotification()
{
Notifications.Remove(NotificationForDeletion);
AddNotificationsToPanel(Notifications, Panel);
}
//Add a delete button:
var del = new Button();
del.Content = "Slet";
del.FontSize = 24;
del.Command = DeleteNotificationCommand;
del.CommandParameter = notification.Id; // <-- unique id
horizontalStackPanel.Children.Add(del);
public ICommand DeleteNotificationCommand
{
get{
return new RelayCommand(DeleteNotification);
}
}
private void DeleteNotification(object parameter)
{
int notificationId = (int)parameter;
var NotificationForDeletion = ...; // <--- Get notification by id
Notifications.Remove(NotificationForDeletion);
AddNotificationsToPanel(Notifications, Panel);
}