我有一个DataGrid样式模板,我希望添加双击行为。绑定应该是正确的,但我似乎无法得到xaml编译/工作。
添加到IDictionary的所有对象都必须具有Key属性 或与其相关的其他类型的密钥。
以下代码有什么问题?
<Style TargetType="{x:Type DataGridRow}">
<EventSetter Event="MouseDoubleClick" Handler="{Binding Connect}"/>
根据Viktor的评论更新(给出完全相同的错误):
<Style x:Key="dataGridRowStyle" TargetType="{x:Type DataGridRow}">
<EventSetter Event="PreviewMouseDoubleClick" Handler="{Binding Connect}"/>
答案 0 :(得分:6)
可以使用DataGrid InputBindings来实现目标:
<DataGrid.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick" Command="{Binding SomeCommand}" />
</DataGrid.InputBindings>
答案 1 :(得分:2)
您可以在数据网格行上应用以下行为,并按照实施用法进行操作。
public class DoubleClickBehavior
{
#region DoubleClick
public static DependencyProperty OnDoubleClickProperty = DependencyProperty.RegisterAttached(
"OnDoubleClick",
typeof(ICommand),
typeof(DoubleClickBehavior),
new UIPropertyMetadata(DoubleClickBehavior.OnDoubleClick));
public static void SetOnDoubleClick(DependencyObject target, ICommand value)
{
target.SetValue(OnDoubleClickProperty, value);
}
private static void OnDoubleClick(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
var element = target as Control;
if (element == null)
{
throw new InvalidOperationException("This behavior can be attached to a Control item only.");
}
if ((e.NewValue != null) && (e.OldValue == null))
{
element.MouseDoubleClick += MouseDoubleClick;
}
else if ((e.NewValue == null) && (e.OldValue != null))
{
element.MouseDoubleClick -= MouseDoubleClick;
}
}
private static void MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
UIElement element = (UIElement)sender;
ICommand command = (ICommand)element.GetValue(OnDoubleClickProperty);
command.Execute(null);
}
#endregion DoubleClick
}
<Style BasedOn="{StaticResource {x:Type DataGridRow}}"
TargetType="{x:Type DataGridRow}">
<Setter Property="Helpers:DoubleClickBehavior.OnDoubleClick" Value="{Binding Path=DataContext.MyCommandInVM, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ViewLayer:MyUserControl}}}" />
</Style>
答案 2 :(得分:2)
不确定你是否要使用MVVM路由,但是我已经使用Attached Command Behavior将双击事件连接到我的viewmodel中的命令(其中“command”是对我的attachCommandBehavior程序集/类):
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="command:CommandBehavior.Event" Value="MouseDoubleClick"/>
<Setter Property="command:CommandBehavior.Command" Value="{Binding SelectItemCmd}"/>
<Setter Property="command:CommandBehavior.CommandParameter" Value="{Binding }"/>
</Style>
</DataGrid.RowStyle>