我有一个LongListSelector,用于存储Azure SQL数据库中的数据。
这是我的C#代码:
private async void RefreshTodoItemsToday()
{
try
{
coll = await todoTable
.Where(todoItem => todoItem.TpEvt == "today")
.ToCollectionAsync();
}
catch (MobileServiceInvalidOperationException e)
{
MessageBox.Show(e.Message, "Error loading items", MessageBoxButton.OK);
}
ListItemstoday.ItemsSource = coll;
}
这是我的XAML:
<phone:LongListSelector Name="ListItemsToday">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="TxtEvt" Text="{Binding Text}" TextWrapping="Wrap" Foreground="Gray" TextAlignment="Center" FontSize="30" Padding="30">
</TextBlock>
<Line X1="0" Y1="10" X2="240" Y2="10" Stroke="SkyBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Height="21"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
寄存器存储在我的LongListSelector中 - 它工作正常。
现在这是我的疑问:我怎样才能读取LongListSelector中每个寄存器的属性?对于每个寄存器,我有“Id”,“TypeEvent”,“Hour”,“Date”等字段。
那么,我如何根据LongListSelector中的SelectedItem读取每个单独的值?
例如,如果我希望在MessageBox中看到来自Selected Item的ID ...我该如何在代码中执行此操作?
我尝试了以下内容:
var tmp1 = (TodoItem)ListItemsToday.SelectedItem;
var tmp2 = tmp1.Id;
MessageBox.Show(tmp2.ToString());
当我尝试转换此代码时,这是我得到的错误:
* System.NullReferenceException:未将对象引用设置为对象的实例。 在Project.MainPage.ContextMenuRemove_Click(Object sender,EventArgs e)*
有人可以帮忙吗? 谢谢各位朋友。
答案 0 :(得分:3)
对选择的反应发生了变化:
<phone:LongListSelector Name="ListItemsToday" SelectionChanged="ListItemsToday_SelectionChanged">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="TxtEvt" Text="{Binding Text}" TextWrapping="Wrap" Foreground="Gray" TextAlignment="Center" FontSize="30" Padding="30">
</TextBlock>
<Line X1="0" Y1="10" X2="240" Y2="10" Stroke="SkyBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Height="21"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
用这个
private void ListItemsToday_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = ListItemsToday.SelectedItem as TodoItem;
MessageBox.Show(item.Text);
}
或对数据模板中的点击事件作出反应
<phone:LongListSelector Name="ListItemsToday" >
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Tap="ListItemsToday_Tap">
<TextBlock Name="TxtEvt" Text="{Binding Text}" TextWrapping="Wrap" Foreground="Gray" TextAlignment="Center" FontSize="30" Padding="30">
</TextBlock>
<Line X1="0" Y1="10" X2="240" Y2="10" Stroke="SkyBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Height="21"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
像这样:
private void ListItemsToday_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
var item = (sender as FrameworkElement).DataContext as TodoItem;
MessageBox.Show(item.Text);
}