我正在寻找一个解决方案,在其中我双击一个DataGridRow,它用一个ICommand在我的ViewModel中调用一个方法。
我为DataGrid的DataGridRow样式编写了以下代码:
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridRow}">
<EventSetter Event="MouseDoubleClick"
Handler="DataGridRow_MouseDoubleClick" />
</Style>
</DataGrid.Resources>这很管用但是..。
我需要在XAML的代码隐藏中使用DataGridRow_MouseDoubleClick方法。然后,在该方法中,我需要在我的ViewModel中调用该方法。
我想绕过代码隐藏,直接用一个ViewModel调用ICommand中的方法。
我发现这段代码很优雅,但是在我(左)双击DataGrid的地方调用该方法。
<DataGrid>
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick"
Command="{Binding MyCallback}" />
</DataGrid.InputBindings>-->
</DataGrid>我只能允许双击一个DataGridRow。
有什么建议吗?
/BR
斯蒂夫
发布于 2022-03-02 13:13:34
可以用执行命令的附加行为替换事件处理程序:
public static class DataGridRowExtensions
{
public static readonly DependencyProperty MouseDoubleClickCommandProperty =
DependencyProperty.RegisterAttached(
"MouseDoubleClickCommand",
typeof(ICommand),
typeof(DataGridRowExtensions),
new FrameworkPropertyMetadata(default(ICommand), new PropertyChangedCallback(OnSet))
);
public static ICommand GetMouseDoubleClickCommand(DataGridRow target) =>
(ICommand)target.GetValue(MouseDoubleClickCommandProperty);
public static void SetMouseDoubleClickCommand(DataGridRow target, ICommand value) =>
target.SetValue(MouseDoubleClickCommandProperty, value);
private static void OnSet(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGridRow row = (DataGridRow)d;
row.MouseDoubleClick += Row_MouseDoubleClick;
}
private static void Row_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
DataGridRow row = (DataGridRow)sender;
ICommand command = GetMouseDoubleClickCommand(row);
if (command != null)
command.Execute(default);
}
}XAML:
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="local:DataGridRowExtensions.MouseDoubleClickCommand"
Value="{Binding DataContext.MyCallback,
RelativeSource={RelativeSource AncestorType=DataGrid}}" />
</Style>发布于 2022-03-02 05:35:29
首先,在项目中安装下面提到的Nuget包。
Microsoft.Xaml.Behaviors.Wpf然后向相关的xaml字段添加以下引用。
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"作为下一步,您可以按以下方式应用双击函数。
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding MyCallback}"/>
</i:EventTrigger>
</i:Interaction.Triggers>https://stackoverflow.com/questions/71311318
复制相似问题