[英]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.