2011-07-01 87 views
0

我有一個datagrid,每行有兩個按鈕 - 一個用於向上移動一行,另一個用於向下移動一行。DataGrid在WPF中的問題

每個按鈕都有一個允許用戶在任一方向移動選定行的命令。我面臨的問題是它無法正常工作。我認爲我可能遇到的問題是行上的其他控件(組合框)通過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; 
     } 

回答

0

你必須操縱CollectionView爲DataGrid。 CollectionView負責基本上你的數據的外觀。這裏是一個小例子:

讓我們假設你已經綁定您的DataGridObservableCollection<T>命名項目,並T有一個名爲指數上排序屬性。
初始化您的視圖模型的ICollectionView這樣的:

private ICollectionView cvs; 

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

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

現在,您可以將您的按鈕命令綁定到命令(在視圖模型也):

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禮貌約什 - 史密斯/卡爾Shifflett的,無法找到了正確的鏈接)

綁定命令,這樣你按鈕(假設你的視圖模型是你的窗口的DataContext):

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

希望這有助於!

+0

謝謝,但我最後通過在幾行代碼中通過MVVM模式在observable類集合上使用move方法做了另一個操作 – Andy5