2011-12-26 64 views
2

我用這個鏈接http://thibaud60.blogspot.com/2010/02/footer-on-wpf-datagrid-by-use-several.html來同步兩個DataGrid,但拖放列標題有時會有bug。WPF:A DataGrid同步B DataGrid with columnWith和DisplayIndex

數據網格具有三個柱:A1,A2,A3

乙數據網格具有三個柱:B1,B2,B3

我SetBinding喜歡:

Binding bindingWidth = new Binding(); 
bindingWidth.Mode = BindingMode.TwoWay; 
bindingWidth.Source = A1; 
bindingWidth.Path = new PropertyPath(DataGridColumn.WidthProperty); 
BindingOperations.SetBinding(B1, DataGridColumn.WidthProperty, bindingWidth); 

Binding bindingDisplayIndex = new Binding(); 
bindingDisplayIndex.Mode = BindingMode.TwoWay; 
bindingDisplayIndex.Source = A1; 
bindingDisplayIndex.Path = new PropertyPath(DataGridColumn.DisplayIndexProperty); 
BindingOperations.SetBinding(B1, DataGridColumn.DisplayIndexProperty, bindingDisplayIndex); 

通常這工作良好,

但我改變了A1 displayindex通過拖動列有時雙向綁定不起作用:

我拖着A3 TO A1位置不成功,但是B3會成功改變位置爲B1

A1.DisplayIndex!= B1.DisplayIndex?

爲什麼會發生這種情況?

回答

0

我用

private static Dictionary<DataGridColumn, DataGridColumn> ColumnCache=new Dictionary<DataGridColumn,DataGridColumn>(); 

存儲到的DataGridColumn和

 dgSource.ColumnDisplayIndexChanged += (sender1, e1) => 
       { 
        var a=ColumnCache[e1.Column]; 
        a.DisplayIndex = e1.Column.DisplayIndex; 
       }; 

改變columnDisplayIndex和錯誤時,我喜歡使用綁定:

Binding bindingDisplayIndex = new Binding(); 
bindingDisplayIndex.Mode = BindingMode.TwoWay; 
bindingDisplayIndex.Source = A1; 
bindingDisplayIndex.Path = new PropertyPath(DataGridColumn.DisplayIndexProperty); 
BindingOperations.SetBinding(B1, DataGridColumn.DisplayIndexProperty, bindingDisplayIndex); 

已經解決。 也許存在columnDisplay變化

0

我花了一些時間來找到很好的辦法之前,一些汽車手柄,所以對於那些誰不想要搜索:-) 謝謝您的幫助

private static Dictionary<DataGridColumn, DataGridColumn> ColumnCache = new Dictionary<DataGridColumn, DataGridColumn>(); 
private static void SynchronizeVerticalDataGrid(DataGrid source, DataGrid associated) 
{ 
    associated.HeadersVisibility = source.HeadersVisibility & (DataGridHeadersVisibility.Row); 
    associated.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden; 

    int sourceColIndex = 0; 
    for (int associatedColIndex = 0; associatedColIndex < associated.Columns.Count; associatedColIndex++) 
    { 
     var colAssociated = associated.Columns[associatedColIndex]; 
     var colSource = source.Columns[sourceColIndex]; 
     sourceColIndex++; 

     ColumnCache.Add(colSource, colAssociated); 

     Binding binding = new Binding(); 
     binding.Mode = BindingMode.TwoWay; 
     binding.Source = colSource; 
     binding.Path = new PropertyPath(DataGridColumn.WidthProperty); 
     BindingOperations.SetBinding(colAssociated, DataGridColumn.WidthProperty, binding); 
    } 

    source.ColumnDisplayIndexChanged += (sender1, e1) => 
     { 
      var a = ColumnCache[e1.Column]; 
      a.DisplayIndex = e1.Column.DisplayIndex; 
     }; 
}