RowDoubleClick
这是一个常见的请求,能够处理双击 RadGridView 中的行。Telerik 提出的解决方案( http://demos.telerik.com/silverlight/#GridView/ClickEvents )基于以下代码:
this.grid.AddHandler(GridViewCellBase.CellDoubleClickEvent, new EventHandler<RadRoutedEventArgs>(OnCellDoubleClick), true);
如果你正在使用 MVVM,你可能更喜欢附加一个 ICommand,它将作为参数传递给已被点击的行的 DataContext。这是如何做到这一点。XAML:
<telerik:RadGridView
ItemsSource="{Binding Rows}"
IsReadOnly="True"
ShowGroupPanel="False"
ShowColumnFooters="True"
local:RadGridViewAttachedProperties.RowDoubleClickCommand="{Binding DoubleClickRow}"/>
AttachedProperty:
public static class RadGridViewAttachedProperties
{
public static readonly DependencyProperty RowDoubleClickCommandProperty =
DependencyProperty.RegisterAttached("RowDoubleClickCommand", typeof(ICommand), typeof(RadGridViewAttachedProperties), new UIPropertyMetadata(null, OnRowDoubleClickCommandChanged));
public static ICommand GetRowDoubleClickCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(RowDoubleClickCommandProperty);
}
public static void SetRowDoubleClickCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(RowDoubleClickCommandProperty, value);
}
private static void OnMouseDoubleClick(object sender, RoutedEventArgs e)
{
var obj = sender as DependencyObject;
if (obj != null)
{
var command = GetRowDoubleClickCommand(obj);
if (command != null)
{
var frameworkElement = e.OriginalSource as FrameworkElement;
var dataContext = frameworkElement?.DataContext;
if (command.CanExecute(dataContext))
{
command.Execute(dataContext);
}
}
}
}
private static void OnRowDoubleClickCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var controlIsTheRightType = d as RadGridView;
if (controlIsTheRightType == null)
{
return;
}
controlIsTheRightType.MouseDoubleClick += OnMouseDoubleClick;
}
}
示例 ViewModel(使用 Telerik DelegateCommand 作为命令;但你可以执行你喜欢的操作):
public class MainWindowViewModel
{
public MainWindowViewModel()
{
Rows = new ObservableCollection<string>();
Rows.Add("kljshndfoa");
DoubleClickRow = new DelegateCommand(e => MessageBox.Show("Hello " + e));
}
public ICommand DoubleClickRow { get; }
public ObservableCollection<string> Rows { get; }
}
注意:你将知道 RadGridView 的 ItemsSource 中的内容类型。在 ICommand 的 Execute 方法中,请确保检查命令的参数类型,因为单击页眉或页脚也会触发此命令; 但在这些情况下,参数将不是你的项目之一。