我正在尋找一種解決方案,在該解決方案中,我雙擊一個 DataGridRow,它使用 ICommand 在我的 ViewModel 中呼叫一個方法。
我的 DataGrid 的 DataGridRow 樣式有以下代碼:
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridRow}">
<EventSetter Event="MouseDoubleClick"
Handler="DataGridRow_MouseDoubleClick" />
</Style>
</DataGrid.Resources>
這可行,但是...
我需要DataGridRow_MouseDoubleClick在 XAML 的代碼隱藏中使用該方法。然后在那個方法中,我需要在我的 ViewModel 中呼叫該方法。
我想繞過代碼隱藏并使用 ICommand 直接呼叫 ViewModel 中的方法。
我發現這段代碼很優雅,但是在我(左)雙擊 DataGrid 的任何地方都會呼叫該方法。
<DataGrid>
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick"
Command="{Binding MyCallback}" />
</DataGrid.InputBindings>-->
</DataGrid>
我只能允許雙擊 DataGridRow。
有什么建議?
/BR
斯蒂夫
uj5u.com熱心網友回復:
您可以將事件處理程式替換為執行命令的附加行為:
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 SetHasFish(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>
uj5u.com熱心網友回復:
首先,在你的專案中安裝下面提到的 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://www.uj5u.com/ruanti/436192.html
