首页 > 解决方案 > WPF ListBoxItem 事件从未被调用

问题描述

我想在 ListBoxItem 上触发事件

        <ListBox.ItemTemplate>

            <DataTemplate>

            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">

               <EventSetter Event="Drop"     
                        Handler="Item_Drop"/>

                <EventSetter Event="PreviewMouseLeftButtonDown" 
                       Handler="Item_PreviewMouseLeftButtonDown"  />
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

在后面的代码中,有两个事件处理程序

    private void Item_Drop(object sender, DragEventArgs e)
    {

    }

    private void Item_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {

    }

事件处理程序永远不会被调用,我做错了什么?

顺便说一句,DataTemplate 包含一个 Grid 控件。我已经尝试使用 Grid 控件上的事件。同样的结果,事件处理程序永远不会被调用或永远不会到达。

标签: wpfeventslistboxitem

解决方案


仅供参考,我没有环境来检查这个。我将描述这个问题及其解决方案。但我可能在代码中有错误。

主要是我不记得默认情况下边框或网格是否伸展。测试这一点的主要事情是应用颜色并尝试使用宽度 + 高度来检查您的事件。

事件设置者很好。这里的问题是没有检测到事件。这样做的原因是您的项目的宽度为 0,高度为 0,因此它不会占用任何空间来单击或放置

另一个原因是颜色。如果拉伸的项目没有颜色,则没有绘制像素,因此即使在那时也不会发生事件。即使应用 Background = "Transparent" 也可以解决问题。

         <ListBox.ItemTemplate>

            <DataTemplate>
                  <Border Background="Red" />  <!-- Or Grid or any thing that stretches out -->  
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">

               <EventSetter Event="Drop"     
                        Handler="Item_Drop"/>

                <EventSetter Event="PreviewMouseLeftButtonDown" 
                       Handler="Item_PreviewMouseLeftButtonDown"  />
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

推荐阅读