简体   繁体   中英

Wpf MVVM Selecting/unSelecting Item in DataGrid

I'm working on an MVVM project and I have this Code in one of the the views:

<GroupBox   Header="Defaut"  BorderBrush="#FF4EA8DE" FontSize="16" Foreground="#FF436EFF"  >
                    <DataGrid Background="Transparent" FontSize="14" CanUserAddRows="False" CanUserDeleteRows="False" IsReadOnly="True" AutoGenerateColumns="False" Style="{x:Null}" 
                              ItemsSource="{Binding ErrorList}">
                        <DataGrid.Columns>
                            <DataGridTextColumn Width="0.5*" Header="{DynamicResource Numéro Cordon}" Binding="{Binding BeadName}"></DataGridTextColumn>
                            <DataGridTextColumn Width="0.5*" Header="{DynamicResource Indice Image}" Binding="{Binding IndiceImage}"></DataGridTextColumn>
                            <DataGridTextColumn Width="0.5*" Header="{DynamicResource Défaut}" Binding="{Binding DispDefault}"></DataGridTextColumn>
                            <DataGridTemplateColumn Header="{DynamicResource Criticité}" Width="0.5*">
                                <DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <Label Content="{Binding IsError, Converter={StaticResource IsErrorToCriticityLevel}, Mode=OneWay}"></Label>
                                    </DataTemplate>
                                </DataGridTemplateColumn.CellTemplate>
                            </DataGridTemplateColumn>

                        </DataGrid.Columns>

                        <DataGrid.CellStyle>
                            <Style TargetType="DataGridCell">
                                <Setter Property="CmdB:CommandBehavior.Event" Value="MouseDown" />
                                <Setter Property="CmdB:CommandBehavior.Command" Value="{Binding DataContext.RobotErrorSelectionChangedCommand, 
                                                                                                RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type controls:MetroWindow}}}"/>
                                <Setter Property="CmdB:CommandBehavior.CommandParameter" Value="{Binding Path=SelectedItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}"/>
                                <Style.Triggers>
                                    <Trigger Property="IsSelected" Value="true">
                                        <Setter Property="BorderBrush" Value="#FF6593CF" />
                                        <Setter Property="Background" Value="#FF6593CF" />
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </DataGrid.CellStyle>

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

What I want to do is to be able to unselect the selected item in this list, however I can't find how to access it.

Here is the code in the ViewModel related to this list:

ObservableCollection<Erreur> _ErrorList;
    public ObservableCollection<Erreur> ErrorList
    {
        get { return _ErrorList; }
        set { _ErrorList = value; RaisePropertyChanged("ErrorList");}
    }


private RelayCommand<Erreur> _RobotErrorSelectionChangedCommand;
    public RelayCommand<Erreur> RobotErrorSelectionChangedCommand
    {
        get
        {
            return _RobotErrorSelectionChangedCommand
                ?? (_RobotErrorSelectionChangedCommand = new RelayCommand<Erreur>(
                (Erreur err) =>
                {
                    if (err != null)
                    {
                        viewservice.OpenDialog(new ErreurImageViewModel(err), ServiceLocator.Current.GetInstance<MainViewModel>());

                    }     
                }));
        }
    }

Thank you for any help or advice.

You can bind the SelectedItem property in the Datagrid to a property in the VM, and to clear the current selection you can just set the property to: null . That way you can deselect the SelectedItem through the code whenever you want.

You would bind it in your View like this:

<DataGrid ItemsSource="{Binding ErrorList}" SelectedItem="{Binding SelectedError}" ...>

Then in your ViewModel you would add:

    private Erreur _selectedError = null;

    public Erreur SelectedError
    {
        get => _selectedError;
        set
        {
            if (_selectedError == value) return;
            _selectedError = value;
            RaisePropertyChanged(nameof(SelectedError));
        }
    }

Whenever you want to clear the selection you can just do:

SelectedError = null;

And if you want to select a specific instance from the code you can do:

SelectedError = myInstanceOfError;

Bind the SelectedError property to the SelectedItem Attribute in your XAML.

XAML:

<DataGrid Background="Transparent" FontSize="14" CanUserAddRows="False" CanUserDeleteRows="False" IsReadOnly="True" AutoGenerateColumns="False" Style="{x:Null}" ItemsSource="{Binding ErrorList}" SelectedItem="{Binding SelectedError}">

C# Property:

private Erreur _SelectedError;
public Erreur SelectedError
{
    get { return _SelectedError; }
    set {
            if(_SelectedError != value)
            {
                 _SelectedErrorList = value; 
                 RaisePropertyChanged("SelectedError");
            }
        }
}

Thank you, both answers are correct with a little modification, I added the :

SelectedItem="{Binding SelectedError}"  in the XAML code.

and I had to comment this part to disable the command from working :

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

now the SelectedError get the Selected Item.Thanx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM