How do i make a clickable listbox?

2019-08-29 10:30发布

问题:

i have a list of users that are bound to a listbox(image and the name of the user) and i want to render this lisbox clickable so whnever i click on a user's image i will be redirected to his account. this is the user control that displays the users:

    <UserControl x:Class="Navigateur.Presentation.UserControlWork.ListeEnfControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:conv="clr-namespace:Navigateur.Presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" Height="Auto" Width="Auto"
             >
    <UserControl.Resources>
        <conv:ByteArrayToImageConverter x:Key="bytearraytoImageConverter" />
    </UserControl.Resources>
    <Grid >
        <ListBox x:Name="_imageList" Margin="10,10,10,0" IsSynchronizedWithCurrentItem="True" ScrollViewer.HorizontalScrollBarVisibility="Visible"  VerticalAlignment="Top" Height="250" BorderThickness="0" MouseLeftButtonDown="Click_Kid" >
            <ListBox.ItemTemplate>
                <DataTemplate DataType="Enfant">
                    <Border CornerRadius="30">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition/>
                            <RowDefinition/>
                        </Grid.RowDefinitions>

                                <Image Grid.Row="0" x:Name="image" Source="{Binding avatar}" Width="50" Height="80"/>
                                <TextBlock Grid.Row="1" x:Name="nom" Text="{Binding prenom}" VerticalAlignment="Center"/>
                    </Grid>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</UserControl>

回答1:

Use Button in place of Image and override template of Button to give it an Image look, so that you can have clickable image.

<Button Grid.Row="0" Width="50" Height="80">
    <Button.Template>
        <ControlTemplate>
            <Image x:Name="image" Source="{Binding avatar}"/>
        </ControlTemplate>
    </Button.Template>
</Button>

If you are using MVVM, you can bind Command with button OR if want to do in code behind you can hook Click event of button to determine which image is clicked on.



标签: c# wpf listbox