WPF: How to decide the position of items while rearranging their order in a ListBox element?

StackOverflow https://stackoverflow.com/questions/5352379

  •  27-10-2019
  •  | 
  •  

문제

I followed the solution to the items rearranging problem provided by dnr3. Works like a charm and it is very easy to understand. Now, I wish to go one step further:

Let's say that ListBox contains items A, B, C, D and E. In the mentioned solution, if a ListBoxItem is moved down the list, it is positioned below the item on which the drop was executed. So, if I select item B and release it over the element D, it will take D's place and D will move one place down. I want to be able to make a difference if the dragged item is closer to the upper or lower target item boundary - if it is closer to the upper I want it placed above the target item, or below if otherwise. I need two things to make that happen:

  1. I need the vertical center point of the target item in order to be able to compare it with mouse position. That should be easy to do:

    targetItem.Height / 2;

  2. I need mouse position relative to the target item. How do I get that?

In the end I want to compare those two values and if mouse position is less than or equal to the item's vertical center point, then the dragged item gets to be dropped before the target item, otherwise below.

Thanks!

도움이 되었습니까?

해결책

Got it! The following line retrieves the mouse position relative to target item
Point p = e.GetPosition(item);

Here's what the drop event handler should look like:

private void PlaylistListBoxItem_Drop(object sender, DragEventArgs e)
{
    ...
    ListBoxItem item;
    int centerY;
    Point p;

    item = sender as ListBoxItem;
    centerY = item.Height / 2;
    p = e.GetPosition(item);

    if (p.Y <= centerY)
    ...
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top