2012-08-04 67 views
0

现在基本上有两个问题在这里,让我轻轻地向你介绍我现在遇到的问题。假设我们有一个常规的DataGrid,并且我尝试在行上应用PreviewMouseRightButtonDown以实现自定义功能,同时避免选择,因为这会扩展Details视图。我认为this post would help; it was directed at ListView, but with few adjustment it should work the same, right?PreviewMouseRightButtonDown路由事件和WPF DataGrid


你为什么要这么做?你可能会问,。 我想避免打开右键单击的详细信息,因为在主项目中,Details部分会使数据库(有时)漫长的行程,而右键单击只会在集合中的视图模型中设置相应的bool标志属性。


MainWindowView.xaml:

<DataGrid AutoGenerateColumns="False" RowDetailsVisibilityMode="VisibleWhenSelected"> 
    <!-- Columns ommitted for brevity --> 
<DataGrid.ItemContainerStyle> 
      <Style TargetType="{x:Type DataGridRow}"> 
      <!-- Since I'm using Caliburn Micro anyway, I'm going to redirect the event to view model. It doesn't really matter, issue exists with EventSetter too. --> 
       <Setter Property="cal:Message.Attach" Value="[Event PreviewMouseRightButtonDown] = [Action CheckItem($eventArgs, $source]"/> 
      </Style> 
     </DataGrid.ItemContainerStyle> 
</DataGrid> 

MainWindowViewModel.cs:

public void CheckItem(RoutedEventArgs args, object source) 
{ 
    var row = source as DataGridRow; 

    if (row != null) 
    { 
     var item = (ItemViewModel)row.Item; 
     item.IsChecked = true; 
    } 

    args.Handled = true; 
} 

问题时间:

  • 为什么在RoutedEventArgsRoutingStrategy列为 Direct而不是Tunneling?我认为所有Preview事件是 Tunneling

enter image description here

  • 而更重要的一个:将上述溶液作品,如果我把一个断点内CheckItem,选择不发生和细节崩溃了,一切正常 如预期。如果我删除断点,则会选择项目,并且 细节部分打开,就好像事件未从 传播一样。为什么会发生?我认为设置 HandledtrueRoutedEventArgs应该只是表明 事件是真的处理

[编辑]

现在我已经找到了一种 '肮脏' 的解决办法,我只能附加PreviewMouseDown事件:

bool rightClick; 

public void MouseDown(object source, MouseEventArgs args) 
{ 
    rightClick = false; 

    if (args.RightButton == MouseButtonState.Pressed) 
    { 
     rightClick = true; 
     //do the checking stuff here 
    } 
} 

,然后挂接到SelectionChanged事件:

public void SelectionChanged(DataGrid source, SelectionChangedEventArgs args) 
{ 
    if (rightClick) 
     source.SelectedIndex = -1;   
} 

它适用于我的特殊情况,但主观上看起来很臭,所以我接受任何其他建议。特别是为什么鼠标事件的简单eventArgs.Handled = true不够后来以抑制:)

+0

@Blam事件触发,它基本上与使用''相同,但这样你就必须在视图后面的代码中处理事件将事件附加到Caliburn的Micro附加属性使您能够在视图模型中处理此事件。尽管如此,即使您使用'EventSetter'并在代码隐藏中执行所有操作,它仍然是相同的 - 事件经过,Details行打开。 – 2012-08-05 00:58:46

回答

0

处理不降反升的PreviewMouseRightButtonUp的SelectionChanged烧制得到预期的效果,我(选择必须向上而不是向下做什么?)。

PreviewMouseRightButtonDown在MSDN页说,它的路由策略应该是“直接”和Routed Events Overview页说:

隧道事件有时也被称为是用来预览事件,因为命名约定的 ,为对。

所以也许隧道事件通常预览事件,但它并没有真正说预览事件有可能是隧道;)

编辑:

综观其他事件,如PreviewMouseDown VS的MouseDown它们虽然是Tunneling和Bubble,但也许只是Right/Left按钮事件是直接完成的。

+0

你说得对,'PreviewMouseRightButtonUp'按我希望的那样工作。奇怪的事情,虽然'PreviewMouseDown'不...无论如何,感谢您指出了这一点,我在这些事件中混合了太多,所以我甚至没有尝试'Up'版本。 :)既然它解决了我的主要问题,我会将其标记为答案。 – 2012-08-06 01:08:12