Search code examples
wpfdatagridinputbinding

WPF DataGrid Left Click only on Row


How can i do a leftclick on a datagrid only enable when a row is selected? here are a example:

<DataGrid>
    <DataGrid.InputBindings>
            <MouseBinding MouseAction="LeftDoubleClick" Command="{Binding LeftClickCommand}"/>
    </DataGrid.InputBindings>
</DataGrid>

Now when i click on no row in the datagrid the command is also executed, but i only wants to execute it when i click on a row.


Solution

  • you can test if the selected item is null this is just a way that maybe help you XAML:

            <Custom1:DataGrid IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Persons}" SelectedItem="{Binding SelectedPerson}"  >
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseDoubleClick">
                    <Custom:EventToCommand CommandParameter="{Binding SelectedItem, ElementName=dg}" Command="{Binding AfficheCommand, Mode=OneWay}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
    

    Code behind :

        private PersonModel _selectedPersons = new PersonModel();
        public PersonModel SelectedPerson
        {
            set
            {
                _selectedPersons = value;
            }
        }
        public ICommand AfficheCommand
        {
            get
            {
                return new DelegateCommand(AfficheText);
            }
        }
    
        private void AfficheText()
        {
            if(_selectedPersons != null)
               MessageBox.Show(_selectedPersons.FirstName);
    
           _selectedPersons  = null;
        }
    

    I know that is not the best way but a way until you found a better idea ;)