2013-05-27 81 views
0

我創建了ListBoxItems一個ListBox並添加MouseDown事件處理程序,以每個ListBoxItems的。顯示ListBoxItems,但是當我點擊ListBoxItem時,事件不會被觸發。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。

+0

就像錯字馬克'item.MouseDown'應該是'item.MouseUp' – WiiMaxx

+0

你的權利。我裝了它;-) – Laokoon

+1

你不能使用ListBox的'SelectionChanged'事件嗎? – Jehof

回答

1

這是因爲ListBoxItem已經處理了左,右鍵點擊,這意味着你的事件處理程序將不會根據WPF路由事件的規則被觸發。你要麼必須分配PreviewMouseDown事件或添加事件處理程序處理事件:

lbi.AddHandler(ListBoxItem.MouseDownEvent, new MouseButtonEventHandler(MouseEvent), true); 
0
void OnListBox_Mouse_Down(object sender, MouseButtonEventArgs e) 
{ 
    e.Handled 
} 

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

使用ContainedControl屬性和設置您的活動:)

kryptonListBox1.ContainedControl.MouseDown += kryptonListBox1_MouseDown_1;