This is probably a really easy fix, but I am inexperienced in working with events so I am just going to ask it.
I have a ListBox with ListBoxItems in it. These ListBoxItems will be binded to a data source so they will change. I need a MouseDown event to be raised when a MouseDown action is performed on any of these ListBoxItem (because I am doing drag and drop). Since the values are changing, I cannot expect to wire the events together in the XAML like 开发者_如何学编程the following
<ListBox Name="ListBox1">
<ListBoxItem MouseDown="MouseDownEventName">Item A</ListBoxItem>
<ListBoxItem MouseDown="MouseDownEventName">Item B</ListBoxItem>
<ListBoxItem MouseDown="MouseDownEventName">Item C</ListBoxItem>
</ListBox>
This would be easy if I had static values, but since the values in the ListBox will change, I would prefer to write the following XAML
<ListBox Name="ListBox1" MouseDown="MouseDownEventName">
//Binded Values
</ListBox>
Then, when the ListBoxItem is selected, it would Bubble the event up to this MouseDownEventName, and I can grab ListBox1.SelectedItem at that time, the problem is, I am trying this right now, but it is not working. I have the following Code to handle the MouseDown, which is only rewriting label content at the moment to signify that the item has been MouseDown'ed.
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void ListBox_MouseDown(object sender, RoutedEventArgs e)
{
ListBox box = (ListBox)sender;
if (box != null && box.SelectedItem != null)
{
DragDrop.DoDragDrop(box, ItemListBox.SelectedItem, DragDropEffects.Move);
label1.Content = "MouseDown Event Fired";
}
}
}
Using XAML, you can provide a template for different types contained within the form. For example, in this case, you can specify that ListBoxItem's fire off a certain event handler. This is the bulk of the XAML markup code (details found here: How to catch Click on ListboxItem when the item is templated?)
<ListBox>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBoxItem_PreviewMouseLeftButtonDown"/>
</Style>
</ListBox.ItemContainerStyle>
...
</ListBox>
Another thing to check before is to try and change your DragDrop.DoDragDrop() method call to something else to see if the issue has to do with that method. Since the Label's content is changing, I would imagine it has something to do with that method.
精彩评论