I have a listbox,inside that item template,and inside that data template(as usual). My aim is- in listbox selection changed event, I want to bind listbox selected item to a image control-and my code is--
ListBox lb = (ListBox)sender;
ListBoxItem item = (ListBoxItem)lb.SelectedItem;
Image im = (Image)item.Content;
Image1.Source = new BitmapImage(((BitmapImage)im.Source).UriSource);
and my ListBox.ItemTemplate
looks like this:
<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>
But it is showing exception. Image1
is my image control and I don't want to bind image source in xaml. I have some certain requirements.
You have excepion because when you bind ListBox
, and I assume you do, or any ItemsControl
for that matter, properties like Items
, SelectedItem
and SelectedItems
will be of a type of bound list item and not ListBoxItem
, which is just a container. If you need ListBoxItem
refer to it like that:
var listBox = sender as ListBox;
var lbi = (ListBoxItem)listBox
.ItemContainerGenerator
.ContainerFromItem(listBox.SelectedItem)
but if your Image
is part of DataTemplate
it won't be as easy as getting Content
. Again it will be of a type of bound item, basically point to the same as SelectedItem
. Maybe you can use that as otherwise you will need to refer to VisualTreeHelper
as by default there will be other controls in visual tree between ListBoxItem
and your DataTemplate
Image
. I undrestand you don't want to bind Image.Source
but why not bind back ListBox.SelectedItem
and then you can refer to your object instead.
If you want to update Image1.Source
with SelectedItem
image then your SelectionChange
method should look like this:
Image1.Source = ((sender as ListBox).SelecteItem as img).Imgs;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.