[英]DataGrid does not execute double click event on editable cells
目標
目標是在選定行上雙擊執行命令。
問題
當我雙擊一個單元格時,它進入編輯模式並且不執行命令。
如果我雙擊Data
列右側的空單元格 - 它會執行命令。
此外,如果我將IsReadOnly
設置為true
,它可以工作.. 它只是不適用於可編輯單元格。
問題
為什么雙擊事件不適用於可編輯單元格?
重現問題的代碼
XAML
<DataGrid ItemsSource="{Binding SampleModels}" SelectedItem="{Binding SelectedItem}" AutoGenerateColumns="True" >
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding Command}" />
</DataGrid.InputBindings>
</DataGrid>
Model
public class SampleModel
{
public int Id { get; set; }
public string Data { get; set; }
}
查看 Model
public class SampleViewModel : BaseViewModel
{
public ObservableCollection<SampleModel> SampleModels { get; set; }
private SampleModel _selectedItem;
public SampleModel SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged();
}
}
private void LoadData()
{
if(SampleModels == null)
{
SampleModels = new ObservableCollection<SampleModel>();
}
SampleModels.Clear();
SampleModels.Add(new SampleModel { Id = 1, Data = "Item 1" });
SampleModels.Add(new SampleModel { Id = 2, Data = "Item 2" });
}
public ICommand Command { get; }
private void TestMethod()
{
var a = SelectedItem;
}
public SampleViewModel()
{
LoadData();
Command = new RelayCommand(param => TestMethod());
}
}
為什么雙擊事件不適用於可編輯單元格?
因為DataGrid
控件通過進入單元格的編輯模式來處理雙擊。 你還能如何編輯單元格?
您可以使用附加行為處理單元格中的雙擊:
public static class DoubleClickBehavior
{
public static ICommand GetCommand(UIElement element) =>
(ICommand)element.GetValue(CommandProperty);
public static void SetCommand(UIElement element, ICommand value) =>
element.SetValue(CommandProperty, value);
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached(
"Command",
typeof(ICommand),
typeof(DoubleClickBehavior),
new UIPropertyMetadata(null, OnChanged));
private static void OnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
UIElement element = (UIElement)d;
if (e.NewValue is ICommand command)
{
element.PreviewMouseLeftButtonDown += OnMouseLeftButtonDown;
}
else
{
element.PreviewMouseLeftButtonDown -= OnMouseLeftButtonDown;
}
}
private static void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2)
{
UIElement element = (UIElement)sender;
ICommand command = GetCommand(element);
if (command != null)
command.Execute(null);
}
}
}
樣品用法:
<DataGrid ItemsSource="{Binding SampleModels}" SelectedItem="{Binding SelectedItem}" AutoGenerateColumns="True" >
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding Command}" />
</DataGrid.InputBindings>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="local:DoubleClickBehavior.Command"
Value="{Binding DataContext.Command,RelativeSource={RelativeSource AncestorType=DataGrid}}" />
</Style>
</DataGrid.CellStyle>
</DataGrid>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.