ListBox with DoubleClick on items using a DataTemplate

I want to know if it is easy to create double-click functionality for ListBox. I have ListBoxwith a collection of both ItemSource. The collection contains its own data types.

<ListBox ItemsSource="{Binding Path=Templates}" 
         ItemTemplate="{StaticResource fileTemplate}">

I defined a DataTemplatefor mine Items, which consists of StackPaneland TextBlocks.

<DataTemplate x:Key="fileTemplate">
     <Border>
         <StackPanel>
              <TextBlock Text="{Binding Path=Filename}"/>
              <TextBlock Text="{Binding Path=Description}"/>
         </StackPanel>
     </Border>
</DataTemplate>

Now I want to detect a double-click event for a double-click list item. I have currently tried with the following, but it does not work, because it does not return the element bound to ListBox, as well TextBlock.

if (TemplateList.SelectedIndex != -1 && e.OriginalSource is Template)
{
    this.SelectedTemplate = e.OriginalSource as Template;
    this.Close();
}

What is a clean way to handle a double-click event on itemin ListBoxif the icons are not ListBoxItems, but their own DataTemplates?

+5
1

, , ...

, ListBoxItem DataTemplate - ...

, - :

    <Window.Resources>
        <DataTemplate x:Key="fileTemplate" DataType="{x:Type local:FileTemplate}">
...
        </DataTemplate>
    </Window.Resources>

    <Grid>

        <ListBox ItemsSource="{Binding Templates}" 
                 ItemTemplate="{StaticResource fileTemplate}">
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <EventSetter Event="MouseDoubleClick" Handler="DoubleClickHandler" />
                </Style>
            </ListBox.ItemContainerStyle>
        </ListBox>

    </Grid>

,

public void DoubleClickHandler(object sender, MouseEventArgs e)
{
    // item will be your dbl-clicked ListBoxItem
    var item = sender as ListBoxItem;

    // Handle the double-click - you can delegate this off to a 
    // Controller or ViewModel if you want to retain some separation
    // of concerns...
}
+12

All Articles