【问题标题】:How to find out which button I pressed?如何找出我按下了哪个按钮?
【发布时间】:2015-05-04 02:19:06
【问题描述】:

想象一下 Facebook 的通知下拉菜单。 我想实现类似的东西。单击“Slet”时,应该从列表中删除该通知。

private void AddNotificationsToPanel(List<Notification> notifications, StackPanel panel)
{
    panel.Children.Clear();


    foreach (var notification in notifications)
    {
        //We want every message to have text, a delete button and a postpone button
        //So we need a nested stackpanel:
        var horizontalStackPanel = new StackPanel();
        horizontalStackPanel.Orientation = Orientation.Horizontal;
        panel.Children.Add(horizontalStackPanel);

        //Display the message:
        var text = new TextBlock();
        text.Text = notification.Message;
        text.Foreground = Brushes.Black;
        text.Background = Brushes.White;
        text.FontSize = 24;
        horizontalStackPanel.Children.Add(text);

        //Add a delete button:
        var del = new Button();
        del.Content = "Slet";
        del.FontSize = 24;
        del.Command = DeleteNotificationCommand;
        horizontalStackPanel.Children.Add(del);

        //Add a postpone button:
        var postpone = new Button();
        postpone.Content = "Udskyd";
        postpone.FontSize = 24;
        postpone.IsEnabled = false;
        horizontalStackPanel.Children.Add(postpone);
    }
    panel.Children.Add(new Button { Content = "Luk", FontSize = 24, Command = ClosePopupCommand });
}

基本上,我有一个垂直堆栈面板,其中有 x 个水平堆栈面板。每个都有一个文本框和两个按钮。 我怎么知道我点击了哪个按钮?这些按钮都绑定到一个删除命令,但我有点不确定它们是如何工作的:

public ICommand DeleteNotificationCommand
{
    get{
        return new RelayCommand(o => DeleteNotification());
    }
}

然后创建这个方法:

private void DeleteNotification()
{
    Notifications.Remove(NotificationForDeletion);
    AddNotificationsToPanel(Notifications, Panel);
}

问题是我们不知道要删除哪个通知,因为我不知道如何查看单击了哪个按钮。有什么想法吗?

【问题讨论】:

标签: c# wpf stackpanel icommand relaycommand


【解决方案1】:

您应该使用按钮的CommandParameter 属性,将每个通知的唯一标识符分配给它。我假设您的通知具有唯一的整数 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);

然后在DeleteNotification方法中,需要为key指定一个参数。

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);
}

现在,您可以在 DeleteNotification 中识别与按钮相关的通知。

【讨论】:

  • 我的 Notification 类中没有标识符,但现在有了!
  • 实际上只要这样写就可以了:return new RelayCommand(DeleteNotification);但是感谢您的帮助!
  • 不客气,是的,我猜这也有效,我更新了答案。
猜你喜欢
  • 1970-01-01
  • 2010-11-06
  • 2020-11-18
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
相关资源
最近更新 更多