gpt4 book ai didi

c# - ListView 中的 MenuFlyout : which element has been clicked

转载 作者:太空宇宙 更新时间:2023-11-03 20:04:55 26 4
gpt4 key购买 nike

我有一个带有评论列表的 ListView:

<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>

评论类:

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

按住评论时出现的 Flyout 菜单在 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;

但是应用程序崩溃了...

最佳答案

您的应用程序崩溃是因为您将 e.OriginalSource 转换为 Comment 并且它不起作用,因为它不是那种类型。通常,通过使用“as”来做到这一点通常更安全

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

关于c# - ListView 中的 MenuFlyout : which element has been clicked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24346364/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com