WPF ListBox Databinding & Events

2019-06-04 00:26发布

问题:

My problem is rather simple.
I have a ListBox, containing Thumnails (Image)

<ListBox Name="ListBox_Thumbnails" ItemsSource="{Binding}" DataContext="{Binding Source= {StaticResource ThumbnailListSource}}" Width="120" HorizontalAlignment="Left" Margin="-1,26,0,54">
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel>
            <Image Source="{Binding Path=absolutePath}" MouseLeftButtonDown=<!--?????-->/>
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

I wanted to show an image, but as a new StackOverFlow user, I can't. You can find the image here:

http://www.freeimagehosting.net/uploads/61aa983cad.jpg

(For those who don't trust me, I explain here the content of the image: On the left, there is a list of thumbnails (displayed vertically) and on the right there is a bigger image, corresponding per default to a large image of the first thumbnail).

When I click on a thumbnail (on the left), the large image on the right should be updated by the one that I clicked on.

As I am new with WPF, my approach is perhaps totally wrong with the ListBox. Please, WPF Gurus, show me the light!

回答1:

I guess, you can use events on ListBox, smth like SelectionChanged... but that's totally not the TRUE WPF-Jedi way -- remember, code-behind is the dark side! =)

Think data binding, that's the Force. Bind your large Image element's source to the SelectedItem property of the ListBox. It should look like

<Image Source="{Binding SelectedItem.absolutePath, ElementName=ListBox_Thumbnails}">

P.S. Every WPF-databinding-jedi should have this cheat sheet nearby.

P.P.S. Actually, as you're using ItemTemplate this might not work, you'll have your StackPanel as the selected item... in this case you can try the SelectedValuePath trick, set it to "absolutePath" and bind the large image to the SelectedValue property.

So your ListBox opening tag becomes:

<ListBox Name="ListBox_Thumbnails" ItemsSource="{Binding}" DataContext="{Binding Source= {StaticResource ThumbnailListSource}}" Width="120" HorizontalAlignment="Left" Margin="-1,26,0,54" SelectedValuePath="absolutePath">

And your large image tag becomes:

<Image Source="{Binding SelectedValue, ElementName=ListBox_Thumbnails}">