I have a ListBox whose ItemSource is a List where X is defined as:
public class X
{
public string FullPath { get; set; }
}
My ViewModel is
public class ViewModel
{
public List<X> MyList { get; set; }
public X MyItem { get; set; }
public ViewModel()
{
MyList = new List<X>
{
new X { FullPath = "q:\\temp\\x1.png"},
new X { FullPath = "q:\\temp\\x2.png"}
};
}
}
And XAML:
<Window x:Class="Bind1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Bind1"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<StackPanel>
<Image Source="{Binding MyItem.FullPath, Mode=OneWay}" HorizontalAlignment="Left" VerticalAlignment="Top" Stretch="None"/>
<ListBox ItemsSource="{Binding MyList}"
SelectedItem="{Binding MyItem, Mode=OneWayToSource}"
SelectionMode="Single">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding FullPath}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Window>
This works when I used the keyboard up and down arrows in the ListBox (the image from the path selected in the ListBox shows up in the <Image>). However, when I click an item with the mouse, the item I click is not selected in the ListBox (the mouse click has no effect). The correct image shows up in the image very briefly (a fraction of a second) then the original image is displayed. What am I doing wrong?
Since you are using StackPanel
, while the Image
changes upon selection change in the ListBox
, the size of the Image
control may change, hence also the location of the ListBox
.
Such case may cause an effect that the list item you click on not be the same item when you release the mouse button, as the item location changed.
There are many workaround, eg fix the size of the Image
control, use Grid
to define a layout, or simply put the Image
after the ListBox
in the StackPanel
I could reproduce the issue and you can fix the image size or move the image control below the listbox. I agree with Evan
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.