2017-06-22 48 views
0

一個有DataGridItemsSource集到DataTableAutoGenerateColumns="True"交替列背景動態列

<DataGrid ItemsSource="{Binding MyDataTable}" AutoGenerateColumns="True" /> 

我怎樣才能使交替列背景呢?我看到的每個解決方案僅適用於靜態列。

我不使用後面的代碼,所以只有XAML解決方案纔是首選,但我會很滿意每一個有價值的答案。

+0

方不要e:爲什麼設置'DataContext'而不是'ItemsSource'? – grek40

+0

你說得對,我在事實上使用了'ItemsSource' :)我從錯誤的地方複製了代碼(我也有從DataGrid派生的我自己的控件,我在那裏使用'DataContext')。我編輯了這個問題。 – bpiec

回答

1

您可以將DataGridCell.Column.DisplayIndex轉換爲布爾值,它在奇數和偶數列索引之間交替。

我在這裏利用擴展WPF工具包中的轉換器,但它應該很容易寫出你自己的。

<xcdg:IndexToOddConverter x:Key="oddConverter"/> 

<Style TargetType="{x:Type DataGridCell}"> 
    <Style.Triggers> 
     <DataTrigger Binding="{Binding Path=Column.DisplayIndex,RelativeSource={RelativeSource Self},Converter={StaticResource oddConverter}}" Value="True"> 
      <Setter Property="Background" Value="{StaticResource AlternatingColumnBackgroundBrush}"/> 
     </DataTrigger> 
    </Style.Triggers> 
</Style> 

您可能想要利用透明背景,以便交替的行顏色和選擇顏色仍然透過單元格顏色。

+0

'IndexToOddConverter'僅在Xceed Toolkit Plus中... – bpiec

+0

@bpiec我100%肯定我有免費版...但如前所述,它只是一個需要索引並返回布爾值的轉換器...如果你沒有預製品,你可以輕鬆寫出你自己的作品。請注意,它是'http:// schemas.xceed.com/wpf/xaml/datagrid'名稱空間的一部分,而不是'http:// schemas.xceed.com/wpf/xaml/toolkit'的一部分。 – grek40

+0

我將這個答案標記爲自從它被首次接受並且真的有效。我創建了自己的'IndexToOddConverter',但可以使用@ mm8提供的解決方案。謝謝! – bpiec

1

創建您自己的轉換器類:

public class OddConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (value == null) 
      return Binding.DoNothing; 

     return (int)value % 2 != 0; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 

<DataGrid ItemsSource="{Binding MyDataTable}" AutoGenerateColumns="True" /> 
    <DataGrid.Resources> 
     <local:OddConverter x:Key="oddConverter" /> 
     <Style TargetType="{x:Type DataGridCell}"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding Path=Column.DisplayIndex,RelativeSource={RelativeSource Self},Converter={StaticResource oddConverter}}" Value="True"> 
        <Setter Property="Background" Value="Silver"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </DataGrid.Resources> 
</DataGrid> 

或者你也可以處理AutoGeneratingColumn事件:

int index = 0; 
private void dgrData_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) 
{ 
    if (index++ % 2 != 0) 
    { 
     e.Column.CellStyle = dgrData.Resources["oddCellStyle"] as Style; 
    } 
} 

<DataGrid Name="dgrData" ItemsSource="{Binding MyDataTable}" AutoGeneratingColumn="dgrData_AutoGeneratingColumn" /> 
    <DataGrid.Resources> 
     <Style x:Key="oddCellStyle" TargetType="{x:Type DataGridCell}"> 
      <Setter Property="Background" Value="Silver"/> 
     </Style> 
    </DataGrid.Resources> 
</DataGrid>