WPF ListBoxItem events never called

戏子无情 提交于 2019-12-11 16:42:36

问题


I want to trigger events on a ListBoxItem

        <ListBox.ItemTemplate>

            <DataTemplate>

            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">

               <EventSetter Event="Drop"     
                        Handler="Item_Drop"/>

                <EventSetter Event="PreviewMouseLeftButtonDown" 
                       Handler="Item_PreviewMouseLeftButtonDown"  />
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

In Code behind, there are the two eventhandlers

    private void Item_Drop(object sender, DragEventArgs e)
    {

    }

    private void Item_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {

    }

The Eventhandlers are never called, what I am doing wrong?

BTW the DataTemplate contains a Grid control. I've already tried to use the events on the Grid control. Same result, the eventhandlers are never called or never reached.


回答1:


FYI, I don't have an environment to check this out. I'll describe the issue and it's resolution. But I might have a mistake in the code.

Mainly i don't remember if Border or grid stretch out by default. The main thing to test this out is to Apply a color and try also Width + Height just to check your events out.

The event setters are fine. The problem here is that the event is not detected. The reason for this is that your Item has a width of 0 and a Height of 0 so it does not take up any space to be clicked on or dropped on

Another reason is the color. If the stretched out item has no color there are no pixels drawn so the events would not occur even then. Even applying Background = "Transparent" would do the trick.

         <ListBox.ItemTemplate>

            <DataTemplate>
                  <Border Background="Red" />  <!-- Or Grid or any thing that stretches out -->  
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">

               <EventSetter Event="Drop"     
                        Handler="Item_Drop"/>

                <EventSetter Event="PreviewMouseLeftButtonDown" 
                       Handler="Item_PreviewMouseLeftButtonDown"  />
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>


来源:https://stackoverflow.com/questions/51281282/wpf-listboxitem-events-never-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!