2014-06-21 51 views
1

我有意见列表的ListView控件:出现MenuFlyout在ListView:元素已经被点击了哪个

public class Comment 
{ 
    public Comment(String id, String user, String text, String date_time) 
    { 
     this.Id = id; 
     this.User = user; 
     this.Text = text; 
     this.DateTime = date_time; 
    } 

    public string Id { get; private set; } 
    public string User { get; private set; } 
    public string Text { get; private set; } 
    public string DateTime { get; private set; } 
} 

弹出菜单:

<ListView ItemsSource="{Binding Comments}"> 
    <ListView.ItemTemplate> 
     <DataTemplate> 
      <Border Background="{Binding User, Converter={StaticResource UsernameToBackgroundColorConverter}}" 
        Margin="0,5" 
        HorizontalAlignment="Stretch" 
        FlyoutBase.AttachedFlyout="{StaticResource FlyoutBase1}" 
        Holding="BorderCommento_Holding"> 
        <StackPanel> 
         <Grid Margin="5"> 
          <Grid.ColumnDefinitions> 
           <ColumnDefinition Width="*" /> 
           <ColumnDefinition Width="Auto" /> 
          </Grid.ColumnDefinitions> 
         <TextBlock Text="{Binding User}" 
             FontSize="20" 
             Grid.Column="0" 
             FontWeight="Bold" 
             Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}"/> 
         <TextBlock HorizontalAlignment="Right" 
             Text="{Binding DateTime}" 
             FontSize="20" 
             Grid.Column="1" 
             Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}"/> 
        </Grid> 
        <TextBlock Margin="5,0,5,5" 
             Text="{Binding Text}" 
             FontSize="20" 
             TextWrapping="Wrap"/> 
       </StackPanel> 
      </Border> 
     </DataTemplate> 
    </ListView.ItemTemplate> 
</ListView> 

评论类当持有评论时在Page.Resources中定义:

<Page.Resources> 
    <MenuFlyout x:Name="flyout1" x:Key="FlyoutBase1"> 
     <MenuFlyoutItem x:Name="ReportCommentFlyout" 
         Text="{Binding User, Converter={StaticResource ReportOrDeleteComment}}" 
         Click="ReportCommentFlyout_Click"/> 
    </MenuFlyout> 
</Page.Resources> 

现在,在ReportCommentFlyout_Click中,我需要知道正在报告/删除的评论ID。 我该怎么办?

我已经试过

string CommentId = ((Comment)e.OriginalSource).Id; 

但应用程序崩溃...

回答

5

你的应用程序崩溃,因为你投e.OriginalSource评论,它不工作,因为这是该类型的不行。通常情况下,它往往是比较安全的方式使用要做到这一点“为”

var comment = someObject as Comment; 
if (comment != null) 
{ 

.... 

} 

关于你的问题,你有没有试过

var menuFlyoutItem = sender as MenuFlyoutItem; 
if (menuFlyoutItem != null) 
{ 
    var comment = menuFlyoutItem.DataContext as Comment; 
    if (comment != null) 
    { 
     string CommentId = comment.Id; 
    } 
} 
+0

完美!它工作,谢谢 –