2014-06-21 115 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

完美!它工作,謝謝 –