目标
目标是在双击选定行时执行命令。
问题
当我双击一个单元格时,它进入编辑模式并且不执行命令。
如果我双击列 Data
右侧的空单元格 - 它会执行命令。
此外,如果我将 IsReadOnly
设置为 true
,它会起作用.. 它只是不适用于可编辑的单元格。
问题
为什么双击事件对可编辑单元格不起作用?
重现问题的代码
XAML
<DataGrid ItemsSource="{Binding SampleModels}" SelectedItem="{Binding SelectedItem}" AutoGenerateColumns="True" >
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding Command}" />
</DataGrid.InputBindings>
</DataGrid>
模型
public class SampleModel
{
public int Id { get; set; }
public string Data { get; set; }
}
查看模型
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());
}
}
答案 0 :(得分:0)
为什么双击事件对可编辑单元格不起作用?
因为 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>