MVVM数据网格选自细胞中复制信息(MVVM DataGrid copy information f

2019-09-19 14:44发布

我使用.NET 4.0 DataGrid中与MVVM模式。 我需要启用用户选择单元格,并从选择的细胞的信息复制到其它数据网格行(通过键盘快捷键或上下文菜单复制/粘贴)。 我试图通过的SelectedItem或发送的SelectedItem为CommandParameter但这个功能只有在全行,而不是与细胞实现这一目标。 (DataGrid绑定到包含与浮点字段对象的ObservableCollection。然后将这些字段映射到数据网格细胞)那么,有没有在WPF MVVM任何解决方案如何DataGrid的细胞从一个行复制到另一个? 在此先感谢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>

视图模型:

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;
    }
}

Answer 1:

我想你可能是后SelectionUnit财产。 将其设置为CellOrRowHeader改变从全行单细胞的选择方法。

你失去了漂亮的“什么行叫什么名字?” 突出但你正专注于单个细胞。 (你也许可以扩展数据网格与当前行的逻辑添加自己的亮点。)

<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" />


文章来源: MVVM DataGrid copy information from selected cells