ListBoxItem MouseUp事件不触发
本文关键字:事件 MouseUp ListBoxItem | 更新日期: 2023-09-27 18:15:36
我用ListBoxItems创建了一个ListBox,并为每个ListBoxItems添加了一个MouseDown事件处理程序。显示了ListBoxItems,但是当我单击ListBoxItem时,Event不会被触发。
如何设置鼠标:
TrackedProcessList.ItemsSource = null;
TrackedProcessList.ItemsSource = this.tracks;
/*... some other code that doesn't matter ... */
ListBoxItem[] items = new ListBoxItem[TrackedProcessList.Items.Count];
for (int i = 0; i < TrackedProcessList.Items.Count; i++)
{
Object obj = TrackedProcessList.Items.GetItemAt(i);
//TrackedProcessList.UpdateLayout();
ListBoxItem item = (ListBoxItem)(TrackedProcessList.ItemContainerGenerator.ContainerFromIndex(i));
if (item != null)
{
item.MouseUp += new MouseButtonEventHandler(ListBoxItem_MouseUp_PostQuestion);
items[i] = item;
}
}
应该调用(但没有)的方法:
private void ListBoxItem_MouseUp_PostQuestion(object sender, EventArgs e)
{
MessageBox.Show("ListBoxItem_MouseUp_fired");
}
我的XAML :
<ListBox x:Name="TrackedProcessList" Height="145" Width="605" ItemsSource="{Binding}" BorderThickness="1,0" IsSynchronizedWithCurrentItem="True">
<DataTemplate>
<TextBlock MouseDown="ListBoxItem_MouseUp_PostQuestion" Text="{Binding Path=programName}" HorizontalAlignment="Stretch" ></TextBlock>
</DataTemplate>
</ListBox>
你知道失败可能在哪里吗?没有错误。事件似乎没有绑定到ListBoxItem。
这是因为ListBoxItem
已经处理左击和右击,这意味着您的事件处理程序将不会根据WPF路由事件规则触发。您必须为已处理的事件分配PreviewMouseDown
事件或添加事件处理程序:
lbi.AddHandler(ListBoxItem.MouseDownEvent, new MouseButtonEventHandler(MouseEvent), true);
void OnListBox_Mouse_Down(object sender, MouseButtonEventArgs e)
{
e.Handled
}
void OnListBox_Mouse_Up(object sender, MouseButtonEventArgs e)
{
"Do Something";
}
使用ContainedControl属性设置事件:)
kryptonListBox1.ContainedControl.MouseDown += kryptonListBox1_MouseDown_1;