2017-09-05 24 views
-1

我有數據網格,我綁定displayindex數據上下文(這並不重要)。我使用一個轉換器,採用相結合的字段名和TABLEID,從我可以提取該列(從數據庫)的順序號字符串參數 但從來沒有發射的轉換器,我認爲這是因爲後備顯示索引與轉換器未觸發

這裏的XAML行:

<DataGridTemplateColumn Header="Col1" DisplayIndex="{Binding CarID, Converter={StaticResource FieldNameToIndex}, FallbackValue=0, ConverterParameter=Col1-9}"> 

這裏的轉換器類:

public class FieldNameToIndex : IValueConverter 
{ 
    public object Convert(object value, Type targetType, 
     object parameter, CultureInfo culture) 
    { 
     string[] data = parameter.ToString().Split('-'); 
     if(data.Length == 2) 
     { 
      long val; 
      if (!long.TryParse(data[1], out val)) 
       return 0; 

      using (AmethystEntities db = new AmethystEntities()) 
      { 
       string fieldName = data[0]; 
       Fields mat = db.Fields.Where(m => m.FieldName == fieldName && val == m.TableID).FirstOrDefault(); 
       if (mat != null) 
        return (mat.DisplayIndex != null ? mat.DisplayIndex : 0); 
      } 
     } 

     return 0;   
    } 

    public object ConvertBack(object value, Type targetType, 
     object parameter, CultureInfo culture) 
    { 
     return value; 
    } 
} 

回答

1

創建綁定程序列已創建:

<DataGrid Loaded="DataGrid_Loaded"> 
    <DataGrid.Columns> 
     <DataGridTemplateColumn x:Name="col1" Header="Col1"> 
     ... 
    </DataGrid.Columns> 
</DataGrid> 

private void DataGrid_Loaded(object sender, RoutedEventArgs e) 
{ 
    BindingOperations.SetBinding(col1, DataGridColumn.DisplayIndexProperty, 
     new Binding("CarID") { Source = this, Converter = new FieldNameToIndex(), FallbackValue = 0 }); 
} 

列獲得創建一個又一個第一列獲得創建的時候有在Columns收集的DataGrid,因此沒有其他列的DisplayIndex只能設置爲0.

+0

作品像魅力謝謝 – user7925257