繁体   English   中英

如何找出我按下的按钮?

[英]How to find out which button I pressed?

从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个水平的堆栈面板。 每个按钮都有一个文本框和两个按钮。 我怎么知道我点击了哪个按钮? 这些按钮都绑定到一个delete命令,但是我不确定它们是如何工作的:

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

然后创建该方法:

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

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

您应该通过为按钮分配每个通知的唯一标识符来使用按钮的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方法中,您需要为密钥指定一个参数。

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中,您可以标识与按钮相关的通知。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM