2015-05-03 44 views
0

在Facebook上查看通知下拉菜单。 我想实现类似的东西。点击“Slet”时,应该从列表中删除该通知。 enter image description here如何找出我按下哪个按钮?

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

基本上,我有具有水平stackpanels的x量的垂直的StackPanel。每个人都有一个文本框和两个按钮。 我如何知道我点击了哪个按钮?这些按钮都绑定到删除命令,但我有点不确定如何工作的:

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

然后创建这个方法:

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

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

+0

我编辑了你的标题。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –

回答

2

您应该使用按钮的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中,您可以确定与该按钮相关的通知。

+0

我的Notification类没有标识符,但我现在就做! –

+0

其实它只是通过编写这个工作:返回新的RelayCommand(DeleteNotification); 但是,感谢您的帮助! –

+0

不客气,是的,我应该猜测这也是可行的,我更新了答案。 –

相关问题