我有一个LongListSelector与某种Items的ObservableCollection绑定。物品有许多不同的属性。
<LongListSelector Name="DraftControl" MouseLeftButtonDown="GoToEditDraft">
<LongListSelector.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
<LongListSelector.ItemTemplate>
</LongListSelector>
它有一个事件处理程序。但它获取整个LongListSelector的发送者,而不是特定的项目。如何为所有项添加事件处理程序?
这是一个处理程序的代码:
private void GoToEditDraft(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
var clickerdItem = (LongListSelector)sender;
MessageBox.Show(clickedItem.SelectedItem.ToString());
}
因此,尝试以这种方式获取SelectedItem会抛出NullReferenceException。
数据模板:
<DataTemplate>
<Grid Margin="10" toolkit:TiltEffect.IsTiltEnabled="True">
<Grid.Background>
<SolidColorBrush Color="LightGray" Opacity="0.8"/>
</Grid.Background>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition MaxHeight="100"/>
<RowDefinition MaxHeight="30"/>
</Grid.RowDefinitions>
<TextBlock TextWrapping="Wrap" FontSize="28" Foreground="{StaticResource CustomApplicationTextBrush}" Text="{Binding Title, Converter={StaticResource SanitizeString}}" Margin="10,10,10,0" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2"/>
<Image Source="/Images/no-image.png" Stretch="UniformToFill" MaxHeight="100" Margin="10,10,0,10" Grid.RowSpan="1" Grid.Column="0" Grid.Row="1" VerticalAlignment="Top"/>
<TextBlock TextWrapping="Wrap" FontSize="18" Foreground="{StaticResource CustomApplicationTextBrush}" TextTrimming="WordEllipsis" Text="{Binding Address, Converter={StaticResource SanitizeString}}" Margin="10,0,10,10" Grid.Column="1" Grid.Row="1" VerticalAlignment="Top"/>
</Grid>
</DataTemplate>
结合:
ObservableCollection<Item> draftItems = new ObservableCollection<Item>();
var draftStorage = IsolatedStorageFile.GetUserStoreForApplication();
IReadOnlyList<StorageFile> allDrafts = await draftFolder.GetFilesAsync();
foreach (StorageFile file in allDrafts)
{
using (var stream = new IsolatedStorageFileStream("Drafts\\" + file.Name, FileMode.Open, draftStorage))
{
var fileReader = new StreamReader(stream);
string jsonContents = fileReader.ReadLine();
Item readedItem = JsonConvert.DeserializeObject<Item>(jsonContents);
draftItems.Add(readedItem);
fileReader.Close();
}
}
DraftControl.ItemsSource = draftItems;
答案 0 :(得分:3)
试试这个。
private void DraftControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var myItem = ((Item)(sender as LongListSelector).SelectedItem);
}
答案 1 :(得分:2)
订阅LongListSelectors SelectionChangedEvent而不是
<LongListSelector Name="DraftControl" SelectionChanged="lls_SelectionChanged">
<LongListSelector.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
<LongListSelector.ItemTemplate>
</LongListSelector>
并获取后面代码中的项目
private void lls_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var myItem = ((LongListSelector) sender).SelectedItem as Type;
}