Get SelectedItem from listbox in code behind
I have a ListBox populated with a list from ImageDomainService (RIA Services). I want to select one image from the ListBox and show the bigger version of the image beside it. Images are stored separate in /images/ folder How do I get the ImageName binding from ListBox to the url string in code behind like below?
void AlbumView_Loaded(object sender, RoutedEventArgs e)
{
ImageDomainContext ctx = new ImageDomainContext();
listBoxImages.ItemsSource = ctx.Images;
ctx.Load(ctx.GetImagesListQuery());
}
XAML:
<ListBox x:Name="listBoxImages" ItemsSource="{Binding}"
SelectionChanged="ListBox_SelectionChanged">
<ListBox.ItemTem开发者_如何学Goplate>
<DataTemplate>
<TextBlock x:Name="ImageNameTextBox" Text="{Binding ImageName}" />
<TextBlock Text="{Binding ImageDescription}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Event Handler:
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Image _image = new Image();
BitmapImage bi = new BitmapImage();
// string url = ???????????
bi.UriSource = new Uri(string.Format("images/{0}", url), UriKind.Relative);
_image.Source = bi;
_image.Width = 500;
_image.Height = 300;
bigImageBorder.Child = _image;
}
Why not just use the SelectedItem property instead?:
// Put the class that you're binding to here...
MyClass instance = listBoxImages.SelectedItem as MyClass;
string url = instance.ImageName; // url is an odd variable name for this...
bi.UriSource = new Uri(string.Format("images/{0}", url), UriKind.Relative);
Also, you could potentially make a IValueConverter for the selected item that did this directly, so you could bind your other image source directly to the selected item, without any code behind.
精彩评论