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 方法中,請確保檢查命令的引數型別,因為單擊頁首或頁尾也會觸發此命令; 但在這些情況下,引數將不是你的專案之一。