从后面的代码中的列表框中获取SelectedItem

时间:2010-01-14 01:25:16

标签: c# silverlight xaml

我有一个ListBox,其中填充了ImageDomainService(RIA Services)中的列表。我想从ListBox中选择一个图像,并在它旁边显示更大的图像版本。图像分别存储在/ 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;
}  

1 个答案:

答案 0 :(得分:1)

为什么不直接使用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,这样您就可以将其他图像源直接绑定到所选项目,而无需任何代码。