[英]Get SelectedItem from listbox in code behind
我有一个列表框,其中装有ImageDomainService(RIA Services)的列表。 我想从列表框中选择一个图像,并在其旁边显示该图像的较大版本。 图像分别存储在/ images /文件夹中,如何从ListBox到后面的代码中的ImageName绑定到URL字符串,如下所示?
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.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="ImageNameTextBox" Text="{Binding ImageName}" />
<TextBlock Text="{Binding ImageDescription}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
事件处理程序:
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;
}
为什么不只使用SelectedItem属性呢?
// 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);
此外,您可能会为直接执行此操作的所选项目创建IValueConverter,因此可以将其他图像源直接绑定到所选项目,而无需任何代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.