views:

126

answers:

1

Hello,

i want to know a double-clicking functionality for a list-box kann easily be build. I have a list-box with a collection as ItemSource. The collection contains own data-types.

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

I defined a data-template for my Items, which consists of StackPanels and TextBoxes.

<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 the double-clicked list-item. Currently i tried with following, but this doesnt work because it doesnt return the Item-bound to list-box but the TextBox.

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 a item in a list-box, if the icons are not ListBoxItems, but own DataTypes?

Would be nice, if there are any advices,

greetings Martin

+2  A: 

I've been playing around with this and I think I've got there...

The good news is, that you can apply a style to your ListBoxItem and apply a DataTemplate - the one does not preclude the other...

In other words, you can have something like the following:

    <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>

and then implement a handler in your Window, like

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...
}
IanR