DataGrid bind command to row select

前端 未结 1 986
孤独总比滥情好
孤独总比滥情好 2020-12-23 12:57

I want to execute a command when the user selects a row in a DataGrid.

I see it is possible to wrap cell contents in buttons (although I don\'t want the button styl

相关标签:
1条回答
  • 2020-12-23 13:18

    You should use "Interactivity" assembly and SelectionChanged event.

    <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding People}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding ID}" />
            <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
        </DataGrid.Columns>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{Binding MyCommand}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </DataGrid>
    

    Where "i" is namespace:

    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    

    Also you can write binding to SelectedItem property of the DataGrid and in the set accessor you can invoke your command, but the first solution that i presented you above is better.

    If you want to invoke command from main view model and pass SelectedItem from DataGrid you can use CommadParameter:

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding MyCommand}" 
            CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    

    When items has own command you can use following code:

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding Path=SelectedItem.MyCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    

    Or if elements has own view model that is assigned to it's DataContext, you can use following code:

     <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding Path=SelectedItem.DataContext.MyCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    
    0 讨论(0)
提交回复
热议问题