WPF中冒泡事件?简单的问题
-
12-10-2019 - |
题
这可能是一个非常简单的解决方案,但是我没有经验,因此我只想问一下。
我有一个带有ListBoxItems的ListBox。这些ListBoxItems将被束缚到数据源,以便它们会更改。当对这些ListBoxItem中的任何一个进行Mousedown动作时,我需要提出一个Mousedown事件(因为我在做拖放)。由于值正在变化,因此我不能期望像以下内容一样将事件连接在一起
<ListBox Name="ListBox1">
<ListBoxItem MouseDown="MouseDownEventName">Item A</ListBoxItem>
<ListBoxItem MouseDown="MouseDownEventName">Item B</ListBoxItem>
<ListBoxItem MouseDown="MouseDownEventName">Item C</ListBoxItem>
</ListBox>
如果我有静态值,这将很容易,但是由于列表框中的值会更改,因此我更喜欢编写以下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.我有以下代码来处理Mousedown,目前仅重写标签内容,以表示该物品已被鼠标。
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";
}
}
}
解决方案
使用XAML,您可以为表单中包含的不同类型提供模板。例如,在这种情况下,您可以从某个事件处理程序中指定ListBoxItem的火灾。这是XAML标记代码的大部分(详细信息: 当项目被模板时,如何捕获单击listBoxItem?)
<ListBox>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBoxItem_PreviewMouseLeftButtonDown"/>
</Style>
</ListBox.ItemContainerStyle>
...
</ListBox>
之前要检查的另一件事是尝试将您的dragdrop.dodragdrop()方法更改为其他内容,以查看问题是否与该方法有关。由于该标签的内容正在改变,因此我想它与该方法有关。
不隶属于 StackOverflow