WPF中DataGrid行的问题

时间:2011-07-01 12:47:56

标签: c# wpf wpfdatagrid

我有一个数据网格,每行有两个按钮 - 一个用于向上移动一个按钮,另一个用于向下移动一行。

每个按钮都有一个命令,允许用户沿任一方向移动所选行。我面临的问题是它无法正常工作。我认为我可能遇到的问题是行上的其他控件(组合框)通过MVVM模型绑定到数据源,我在操作XAML后面的代码上的行,认为这将是合理的位置。要做到这一点。

我对其中一个按钮的代码如下:

private void MoveRowDown(object sender, ExecutedRoutedEventArgs e)
        {

            int currentRowIndex = dg1.ItemContainerGenerator.IndexFromContainer(dg1.ItemContainerGenerator.ContainerFromItem(dg1.SelectedItem));

            if (currentRowIndex >= 0)
            {
                this.GetRow(currentRowIndex + 1).IsSelected = true;
            }


        }
private DataGridRow GetRow(int index)
        {
            DataGridRow row = (DataGridRow)dg1.ItemContainerGenerator.ContainerFromIndex(index);
            if (row == null)
            {
                dg1.UpdateLayout();
                dg1.ScrollIntoView(selectedAttributes.Items[index]);
                row = (DataGridRow)dg1.ItemContainerGenerator.ContainerFromIndex(index);
            }
            return row;
        }

1 个答案:

答案 0 :(得分:0)

您必须操纵DataGrid的CollectionView。 CollectionView基本上负责您的数据的样子。这是一个小例子:

假设您已将DataGrid绑定到名为 Items ObservableCollection<T>,并且T具有名为 Index 的属性>对其进行分类。
像这样初始化ViewModel中的ICollectionView

private ICollectionView cvs;

ctor(){
    /*your default init stuff*/
    /*....*/

    cvs = CollectionViewSource.GetDefaultView(items);
    view.SortDescriptions.Add(new SortDescription("Index",ListSortDirection.Ascending));
}

现在您可以将按钮命令绑定到Up命令(也在ViewModel中):

private ICommand upCommand;
public ICommand Up
{
    get { return upCommand ?? (upCommand = new RelayCommand(p => MoveUp())); }
}

private void MoveUp()
{
    var current = (Item)view.CurrentItem;
    var i = current.Index;
    var prev = Items.Single(t => t.Index == (i - 1));
    current.Index = i - 1;
    prev.Index = i;
    view.Refresh(); //you need to refresh the CollectionView to show the changes.
}

警告:您必须添加检查以查看是否有上一个项目等。或者您可以指定一个CanExecute委托,它检查项目的索引并启用/禁用该按钮。 /> RelayCommand由Josh Smith / Karl Shifflett提供,找不到正确的链接了)

将命令绑定到这个按钮(假设您的viewmodel是窗口的DataContext):

<DataGridTemplateColumn >
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <Button Content="Up" 
                  Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, 
                   Path=DataContext.Up}"/>
    </DataTemplate>
  </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>  

希望这有帮助!