3
votes

I’m using .Net 4.0 DataGrid with MVVM pattern. I need to enable user to select cells and copy information from selected cells to other DataGrid rows (either via keyboard shortcut or context-menu copy/paste). I tried to achieve this via SelectedItem or sending SelectedItem as CommandParameter but this functions only with the whole row and not with cells. (DataGrid is bound to ObservableCollection that contains objects with float fields. These fields are then mapped to DataGrid cells) So, is there any solution in WPF MVVM how to copy DataGrid cells from one row to another? Thanks in advance xaml:

    <DataGrid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="9" AutoGenerateColumns="False"     Height="Auto" HorizontalAlignment="Left" 
Name="dataGrid" VerticalAlignment="Top" Width="{Binding ElementName=grid4,Path=Width}"
ScrollViewer.CanContentScroll="False" FrozenColumnCount="1" SelectionUnit="Cell" SelectionMode="Extended" CanUserSortColumns = "False" 
CanUserReorderColumns="False" CanUserResizeRows="False" RowHeight="25" RowBackground="LightGray" AlternatingRowBackground="White"
ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Visible"
ItemsSource="{Binding Layers, Mode=TwoWay}"  SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Selection, Mode=TwoWay}">
 <DataGrid.InputBindings>
    <KeyBinding Gesture="Shift" Command="{Binding ItemHandler}" CommandParameter="{Binding ElementName=dataGrid, Path=SelectedItems}"></KeyBinding>
</DataGrid.InputBindings>

ViewModel:

private float _selection = 0.0f;
public float Selection
{
    get
    {
        return _selection;
    }
    set
    {
        if (_selection != value)
        {
            _selection = value;
            NotifyPropertyChanged("Selection");
        }
    }
}

...

public DelegateCommand<IList> SelectionChangedCommand = new DelegateCommand<IList>(
    items =>
    {
        if (items == null)
        {
            NumberOfItemsSelected = 0; 
            return;
        }
        NumberOfItemsSelected = items.Count;
    });
public ICommand ItemHandler
{
    get
    {
        return SelectionChangedCommand;
    }
}
1

1 Answers

1
votes

I think you might be after the SelectionUnit property. Setting this to CellOrRowHeader changes the selection method from full row to a single cell.

You do lose the nice "what row am I on?" highlighting but you are focusing on a single cell. (You could probably extend the datagrid to add your own highlight with the current row logic.)

<DataGrid AutoGenerateColumns="True" Grid.Column="1" Grid.Row="0"
          HorizontalAlignment="Stretch" Name="dataGrid" VerticalAlignment="Stretch"
          DataContext="{Binding}" ItemsSource="{Binding Path=MyDataTable}"
          IsReadOnly="True" SelectionMode="Extended" SelectionUnit="CellOrRowHeader" />