MVVM DataGrid从选定单元格复制信息

时间:2012-07-17 08:10:43

标签: mvvm .net-4.0 datagrid wpfdatagrid selecteditem

我正在使用带有MVVM模式的.Net 4.0 DataGrid。我需要允许用户选择单元格并将信息从选定的单元格复制到其他DataGrid行(通过键盘快捷键或上下文菜单复制/粘贴)。我试图通过SelectedItem实现这一点,或者将SelectedItem作为CommandParameter发送,但这只对整行而不是单元格起作用。 (DataGrid绑定到包含具有float字段的对象的ObservableCollection。然后将这些字段映射到DataGrid单元格) 那么,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;
    }
}

1 个答案:

答案 0 :(得分: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" />