现在基本上有两个问题在这里,让我轻轻地向你介绍我现在遇到的问题。假设我们有一个常规的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;
}
问题时间:
- 为什么在
RoutedEventArgs
的RoutingStrategy
列为Direct
而不是Tunneling
?我认为所有Preview
事件是Tunneling
。
- 而更重要的一个:将上述溶液作品,如果我把一个断点内
CheckItem
,选择不发生和细节崩溃了,一切正常 如预期。如果我删除断点,则会选择项目,并且 细节部分打开,就好像事件未从 传播一样。为什么会发生?我认为设置Handled
到true
在RoutedEventArgs
应该只是表明 事件是真的处理。
[编辑]
现在我已经找到了一种 '肮脏' 的解决办法,我只能附加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
不够后来以抑制:)
@Blam事件触发,它基本上与使用' '相同,但这样你就必须在视图后面的代码中处理事件将事件附加到Caliburn的Micro附加属性使您能够在视图模型中处理此事件。尽管如此,即使您使用'EventSetter'并在代码隐藏中执行所有操作,它仍然是相同的 - 事件经过,Details行打开。 –
2012-08-05 00:58:46