[英]binding image control to listbox selected item
我有一个列表框,位于项目模板的内部,以及位于数据模板的内部(与往常一样)。 我的目标是-在列表框选择更改事件中,我想将列表框选择的项目绑定到图像控件-我的代码是-
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
, SelectedItem
和SelectedItems
之类的属性都将是绑定列表项的类型,而不是ListBoxItem
,它只是容器。 如果您需要ListBoxItem
像这样引用它:
var listBox = sender as ListBox;
var lbi = (ListBoxItem)listBox
.ItemContainerGenerator
.ContainerFromItem(listBox.SelectedItem)
但是如果您的Image
是DataTemplate
一部分,它将不会如获得Content
那样容易。 同样,它将是一种绑定项,基本上指向与SelectedItem
相同的项。 也许您可以使用它,否则您将需要引用VisualTreeHelper
,因为默认情况下, ListBoxItem
和您的DataTemplate
Image
之间的可视树中将存在其他控件。 我不理解您不想绑定Image.Source
但是为什么不绑定回ListBox.SelectedItem
,然后可以引用您的对象。
如果要使用SelectedItem
图像更新Image1.Source
,则SelectionChange
方法应如下所示:
Image1.Source = ((sender as ListBox).SelecteItem as img).Imgs;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.