I have a binding for ListBox but how I can add an event to selected item?
MainPage.xaml:
<!--ContentPanel - place additional content here-->
<StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Name="list" SelectionChanged="list_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ImageUri}"
Stretch="None"
Height="100"/>
<StackPanel Width="360" >
<TextBlock Text="{Binding Text}"
Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding Opis}"
Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
MainPage.xaml.cs:
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
ObservableCollection<SampleData> dataSource =
new ObservableCollection<SampleData>();
dataSource.Add(new SampleData()
{
ImageUri = "Images/appbar.delete.rest.png",
Text = "Item1",
Description = "blablabla"
});
dataSource.Add(new SampleData()
{
ImageUri = "Images/appbar.delete.rest.png",
Text = "Item2",
Description = "blablabla"
});
dataSource.Add(new SampleData()
{
ImageUri = "Images/appbar.download.rest.png",
Text = "Item3",
Description = "blablabla"
});
this.list.ItemsSource = dataSource;
}
private void list_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (list.SelectedItem == null) return;
//what next?
}
public class SampleData
{
public string Text { get; set; }
public string Description { get; set; }
public string ImageUri { get; set; }
}
}
I want to click for example on Item2 and get to page Page2.xaml.
My project from VS2010: http://www.przeklej.pl/plik/wp7sampleproject6-7z-00368v7i196u
If you are using an MVVM stack like MVVMlight this is quite simple as you simply create a Full Property in your view model for a Selected Item and then bind to it as you would with anything else. Using your code above for example I would do:
Then in your Listbox XAML just bind the Listbox Selected Item to the above property (provided you have set the data context property:
That way you can query the Selected Item Property to find the value.