ListBox WPF中的条件绑定

时间:2014-04-05 11:50:23

标签: c# wpf data-binding listbox

我有一个实现拖放的列表框。我绑定了SelectedItem和SelectedIndex属性。只要有鼠标按下事件,就会设置SelectedItem和SelectedIndex属性。如果只有拖放操作,如何防止它被设置?我尝试覆盖了previewleftbuttondown,但没有成功。有任何想法吗?我需要一些东西:

       TimeSpan difference = DateTime.Now - mousePressedTime;

        if (difference.TotalSeconds >= 3)
        {
            // long press
            //SelectedIndex  and SelectedItem should not be set.
        }
        else
        {
            // short press
            //SelectedIndex  and SelectedItem should be set.
        }

1 个答案:

答案 0 :(得分:0)

我终于找到了解决方案。但我无法对绑定做任何事情。我做的是创建了自己的Listbox并挂钩了PreviewMouseLeftButtonDown和PreviewMouseLeftButtonUp事件。我在列表框的SelectedItem和SelectedIndex属性中执行了什么逻辑,我不得不将它移动到其他地方。代码如下,希望它能提供更好的想法:

 public class DragDropListBox : ListBox
 {
    private static DateTime mousePressedTime;

    public DragDropListBox()
    {
      this.PreviewMouseLeftButtonDown += PreviewMouseLeftButtonDownHandler;
      this.PreviewMouseLeftButtonUp   += PreviewMouseLeftButtonUpHandler;
    }

    private void PreviewMouseLeftButtonDownHandler(object sender, MouseButtonEventArgs e)
    {
      mousePressedTime    = DateTime.Now;
    }

    private void PreviewMouseLeftButtonUpHandler(object sender, MouseButtonEventArgs e)
    {
      TimeSpan difference = DateTime.Now - mousePressedTime;

      if (difference.TotalSeconds <= 1)
      {
        // short press
        if (SelectedItem != null)
        {
            // do what ever you have to
        }
      }
      UnselectAll();
    }
 }