【问题标题】:ListBox with DoubleClick on Items using DataTemplate使用 DataTemplate 对项目进行 DoubleClick 的 ListBox
【发布时间】:2009-12-10 07:36:46
【问题描述】:

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

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

我为我的Items 定义了一个DataTemplate,它由StackPanels 和TextBlocks 组成。

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

现在我想检测双击列表项的双击事件。目前我尝试了以下操作,但它不起作用,因为它不会返回绑定到 ListBox 而是 TextBlock 的项目。

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

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

【问题讨论】:

    标签: c# wpf events event-handling listbox


    【解决方案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...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-13
      相关资源
      最近更新 更多