Вы не можете добавить триггер взаимодействия в Style
. Это не поддерживается.
Вместо этого вы можете определить прикрепленное поведение, которое подключает обработчик событий:
public class SelectionChangedBehavior
{
public static ICommand GetCommand(DataGrid dataGrid)
{
return (ICommand)dataGrid.GetValue(CommandProperty);
}
public static void SetCommand(DataGrid dataGrid, ICommand value)
{
dataGrid.SetValue(CommandProperty, value);
}
public static object GetCommandParameter(DataGrid dataGrid)
{
return dataGrid.GetValue(CommandParameterProperty);
}
public static void SetCommandParameter(DataGrid dataGrid, object value)
{
dataGrid.SetValue(CommandParameterProperty, value);
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached(
"Command",
typeof(ICommand),
typeof(SelectionChangedBehavior),
new UIPropertyMetadata(null, OnCommandChanged));
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.RegisterAttached(
"CommandParameter",
typeof(object),
typeof(SelectionChangedBehavior),
new UIPropertyMetadata(null));
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = d as DataGrid;
if (dataGrid != null)
dataGrid.SelectionChanged += OnSelectionChanged;
}
private static void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dataGrid = (DataGrid)sender;
ICommand command = GetCommand(dataGrid);
if (command != null)
command.Execute(GetCommandParameter(dataGrid));
}
}
XAML:
<Style TargetType="DataGrid" xmlns:local="clr-namespace:WpfApp1">
<Setter Property="IsReadOnly" Value="True" />
<Setter Property="AutoGenerateColumns" Value="False" />
<Setter Property="local:SelectionChangedBehavior.Command" Value="{Binding UpdateSelection}" />
<Setter Property="local:SelectionChangedBehavior.CommandParameter" Value="{Binding SelectedItem}" />
</Style>
WpfApp1
относится к пространству имен класса SelectionChangedBehavior
в приведенном выше примере.