使用DataTemplate在项目上使用DoubleClick的ListBox

时间:2009-12-10 07:36:46

标签: c# wpf events event-handling listbox

我想知道是否可以轻松构建ListBox的双击功能。我有一个ListBox,其集合为ItemSource。该集合包含自己的数据类型。

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

我为DataTemplate定义了Items,其中包含StackPanelTextBlock s。

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

现在我想检测双击列表项的双击事件。目前我尝试使用以下内容,但它不起作用,因为它不会返回绑定到ListBoxTextBlock的项目。

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

如果图标不是item,而是拥有ListBox,那么在ListBoxItems DataTemplates处理双击事件的简洁方法是什么?

1 个答案:

答案 0 :(得分:12)

我一直在玩这个,我想我已经到了那里......

好消息是,您可以将样式应用于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>

然后在你的Window中实现一个处理程序,比如

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...
}
相关问题