wpf - 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 控件上的事件。同样的结果,事件处理程序永远不会被调用或永远不会到达。
解决方案
仅供参考,我没有环境来检查这个。我将描述这个问题及其解决方案。但我可能在代码中有错误。
主要是我不记得默认情况下边框或网格是否伸展。测试这一点的主要事情是应用颜色并尝试使用宽度 + 高度来检查您的事件。
事件设置者很好。这里的问题是没有检测到事件。这样做的原因是您的项目的宽度为 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>
推荐阅读
- angular - *ngFor 中的 Angular 5 输入未正确填充内容
- c - 直接内存映射 GCC 交叉编译
- laravel - Laravel - Session flash 没有显示错误信息的内容
- vue.js - Vue组件在卡内被切断
- android - 某些设备上的 Unity 2D,所有图像变为粉红色
- c - C:如何遍历 `signed int` 的所有可能值,从 `INT_MIN` 到 `INT_MAX`?
- python - 如何从头开始训练 gpt 2?
- c++ - 指向派生类成员的 C++ 指针
- azure - Azure documentDB 是否提供条件写入?
- ios - 使用 Swift 5.1 编译的模块不能被 Swift 5.1.3 编译器导入