【发布时间】:2015-07-31 08:03:00
【问题描述】:
我有一个 ListBox,它显示来自 Web 服务的 cmets 列表。当我运行应用程序时,cmets 显示正常。现在我想使用 ListBox 的选定项的对象的属性,并获取 ID,然后将其分配给字符串值。当我现在运行该应用程序并单击评论以选择它时,我在 Visual Studio 中得到一个 Null 异常。然后我在代码行上设置了一个断点并尝试在鼠标悬停时获取值,它返回了所有对象,但它们都是空的。 代码如下:
<ListBox x:Name="lbxComments" Margin="0,0,-12,0"
ItemsSource="{Binding CommentList,Mode=TwoWay}"
SelectionChanged="lbxComments_SelectionChanged"
>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="480"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image Stretch="UniformToFill" Height="50" Width="50" Source="{Binding profile_pic}" Margin="8" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Border Grid.ColumnSpan="2" Grid.Row="0" HorizontalAlignment="Stretch" BorderBrush="Black" BorderThickness="0,0,0,0.5"/>
<StackPanel Grid.Column="1" >
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Left" FontSize="20" Text="{Binding comment}" TextWrapping="Wrap" TextTrimming="WordEllipsis" Foreground="White" />
<StackPanel Orientation="Horizontal" Margin="0,0,0,5">
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Left" FontSize="16" Text="{Binding fname}" Foreground="White"/>
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Left" FontSize="16" Text="{Binding lname}" Margin="10 0 0 0" Foreground="White"/>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Replies"/>
<TextBlock Text="("/>
<TextBlock Text="{Binding totalreplies}"/>
<TextBlock Text=")" />
</StackPanel>
</StackPanel>
</StackPanel>
</StackPanel>
<TextBlock x:Name="replyTextBox" Grid.Row="2" Margin="50,0,0,0" Visibility="Collapsed" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
在后面的代码中:
private void lbxComments_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedCommentId;
Comment comment = ((sender as FrameworkElement).DataContext) as Comment;
comment = new Comment();
if (comment.id != null)
{
selectedCommentId = comment.id;
repliesViewModel.SetAddress(selectedCommentId);
}
... lbxComments 绑定的 CommentList 是一种 Comment
public class Comment
{
public string fname { get; set; }
public string lname { get; set; }
public string profile_pic { get; set; }
public string id { get; set; }
public string username { get; set; }
public string comment { get; set; }
public string totalreplies { get; set; }
}
所以现在我不知道为什么当我尝试获取所选项目对象时它返回 null,但在列表框中显示正常
【问题讨论】:
标签: c# windows-phone-8 listbox