简体   繁体   English

ListBoxItem MouseUp事件不会触发

[英]ListBoxItem MouseUp Event doesnt fire

I created a ListBox with ListBoxItems and add an MouseDown event handler to each of the ListBoxItems. 我用ListBoxItems创建了一个ListBox,并将MouseDown事件处理程序添加到每个ListBoxItems。 The ListBoxItems are shown, but when I click on a ListBoxItem, the Event doesn't get fired. 显示了ListBoxItems,但是当我单击ListBoxItem时,不会触发该事件。

How i set the MouseUp: 我如何设置MouseUp:

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;
    }
}

The Method which should be called (but it isn't): 应该调用的方法(但不是):

private void ListBoxItem_MouseUp_PostQuestion(object sender, EventArgs e)
{
    MessageBox.Show("ListBoxItem_MouseUp_fired");
}

My XAML: 我的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>

Do you have any ideas where the failure could be? 您对失败的可能有什么想法吗? There is no error. 没有错误。 The Event just seems to be not bound to the ListBoxItem. 该事件似乎没有绑定到ListBoxItem。

It is because ListBoxItem already handles both left and right click which means your event handler will not be triggered according to WPF routed event rules. 这是因为ListBoxItem已经处理了左键单击和右键单击,这意味着将不会根据WPF路由事件规则触发事件处理程序。 Your either have to assign PreviewMouseDown event or add event handler for handled events: 您必须分配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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM