ListBoxItem MouseUp事件不会触发

时间:2013-05-27 11:14:19

标签: c# wpf event-handling

我使用ListBoxItems创建了一个ListBox,并为每个ListBoxItems添加一个MouseDown事件处理程序。显示了ListBoxItems,但是当我单击ListBoxItem时,事件不会被触发。

我如何设置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;
    }
}

应调用的方法(但不是):

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。

3 个答案:

答案 0 :(得分:1)

这是因为ListBoxItem已经处理了左右键单击,这意味着不会根据WPF路由事件规则触发事件处理程序。您必须为已处理事件分配PreviewMouseDown事件或添加事件处理程序:

lbi.AddHandler(ListBoxItem.MouseDownEvent, new MouseButtonEventHandler(MouseEvent), true);

答案 1 :(得分:0)

void OnListBox_Mouse_Down(object sender, MouseButtonEventArgs e)
{
   e.Handled
}

void OnListBox_Mouse_Up(object sender, MouseButtonEventArgs e)
{
   "Do Something";
}

答案 2 :(得分:0)

使用ContainedControl属性并设置事件:)

kryptonListBox1.ContainedControl.MouseDown += kryptonListBox1_MouseDown_1;