简体   繁体   中英

How do I handle a selected item of LongListMultiSelector?

I have list of items in LongListMultiSelector - how to handle a selected item?

My LongListMultiSelector xaml:

<tkit:LongListMultiSelector Name="longlist" SelectionChanged="longlist_SelectionChanged">
    <tkit:LongListMultiSelector.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Title}" FontSize="32" Tap="TextBlock_Tap"/>
        </DataTemplate>
    </tkit:LongListMultiSelector.ItemTemplate>
</tkit:LongListMultiSelector>

TextBlock tap event handler code:

private void TextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
    var itemTapped = (sender as FrameworkElement).DataContext as Book;
}

LongListMultiSelector SelectionChanged event handler code:

private void longlist_SelectionChanged(object sender, SelectionChangedEventArgs e)
{

}

I found part of solution here , however, The problem if at least one item is selected, then textblockTap event doesn't handle - longlist_SelectionChanged event handles everything. How can i fix that?

Once you are using LongListMultiSelector , the SelectionChanged event is fired when item is added or removed. If you want to perform the action regardless item is added/removed, I've managed to do it like this (for a simle string):

private void longlist_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string selectedItem = String.Empty;
    if (e.AddedItems.Count > 0) selectedItem = e.AddedItems[0] as string;
    else selectedItem = e.RemovedItems[0] as string;
    MessageBox.Show(selectedItem); // do your work
}

It should run while items are selected separately by tapping, but this method will have problems when more items are added/removed at the same time - if you need it, then you should handle this also.

Your XAML DataTemplate.

    <DataTemplate x:Key="listItemTemplate">
        <StackPanel Orientation="Horizontal" Margin="4,4">
            <TextBlock Tap="textblockTap" Margin="0,-7,0,0" Text="{Binding Name}" Style="{StaticResource PhoneTextLargeStyle}"/>
        </StackPanel>
    </DataTemplate>

In your CS page;

    private void textblockTap(object sender, EventArgs e)
    {
            var file = (TextBlock)sender;
            var ContentFile = (string)file.Text;
            MessageBox.Show(ContentFile);
    }

This example will show you the text of the selected item in the MessageBox.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM