将图像控件绑定到列表框选定项

本文关键字:列表 图像 控件 绑定 | 更新日期: 2023-09-27 18:15:28

我有一个列表框,在项目模板中,在数据模板中(像往常一样)。我的目标is-在列表框选择更改事件中,我想将列表框选择项绑定到图像控件-我的代码是——

ListBox lb = (ListBox)sender;
ListBoxItem item = (ListBoxItem)lb.SelectedItem;
Image im = (Image)item.Content;
Image1.Source = new BitmapImage(((BitmapImage)im.Source).UriSource);

和我的ListBox.ItemTemplate看起来像这样:

<ListBox Name="imageList" Height="556" Width="130" HorizontalAlignment="Left" Style="{StaticResource ListBoxStyle1}" SelectionChanged="imageList_SelectionChanged" >
   <ListBox.ItemTemplate>
      <DataTemplate>
         <Image Source="{Binding Imgs}" Width="100" Height="100"/>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

但它显示异常。Image1是我的图像控件,我不想在xaml中绑定图像源。我有一些要求

将图像控件绑定到列表框选定项

您有例外,因为当您绑定ListBox时,我假设您这样做,或者任何ItemsControl,属性如Items, SelectedItemSelectedItems将属于绑定列表项的类型,而不是ListBoxItem,这只是一个容器。如果您需要ListBoxItem,请像这样引用它:

var listBox = sender as ListBox;
var lbi = (ListBoxItem)listBox
                         .ItemContainerGenerator
                         .ContainerFromItem(listBox.SelectedItem)

但如果你的ImageDataTemplate的一部分,它不会像获得Content那么容易。同样,它将是绑定项的类型,基本上指向与SelectedItem相同。也许你可以使用它,否则你将需要参考VisualTreeHelper,因为默认情况下,在ListBoxItemDataTemplate Image之间的可视树中会有其他控件。我理解你不想绑定Image.Source,但为什么不绑定回ListBox.SelectedItem,然后你可以引用你的对象。

如果你想用SelectedItem的图像更新Image1.Source,那么你的SelectionChange方法应该是这样的:

Image1.Source = ((sender as ListBox).SelecteItem as img).Imgs;