2017-08-23 48 views
0

有沒有方法將轉換器附加到GridView中的每個單元格以允許根據文本內容更改顏色?使用Converter for DataGrid中的單元格與AutoGenerateColumns

Datagrid帶顏色的樣本。它應該是什麼樣子。

Datagrid sample with color

XAML

[![<DataGrid x:Name="dgvData" AutoGenerateColumns="True" />][1]][1] 

代碼隱藏

Dim tableView As DataView = New DataView(DataTable) 
    Me.dgvData.ItemsSource = tableView 

我所做的迄今使用的樣式和連接的轉換器。 但是在風格上,我無法訪問數據。在數據中,如果它是自動生成的,我沒有包含單元格背景顏色。

+0

檢查[此Q + A](https://stackoverflow.com/questions/45701332)。創建一個轉換器,創建一個DataGridCell樣式,使用轉換器根據值更改顏色,將該樣式分配給DataGrid.CellStyle屬性 – ASh

回答

0

您可以通過綁定到Content.Text屬性來做到這一點。

樣品轉換器:

public class MyConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var x = value; 
     return x.ToString() == "1" ? Brushes.Red : Brushes.Green; 
    } 

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

樣品XAML:

<Window.Resources> 
     <local:MyConverter x:Key="Conv"/> 
    </Window.Resources> 
    <StackPanel> 
     <DataGrid x:Name="dgvData" AutoGenerateColumns="True"> 
      <DataGrid.CellStyle> 
       <Style TargetType="DataGridCell"> 
        <Setter Property="Background" Value="{Binding Content.Text,RelativeSource={RelativeSource Self}, Converter={StaticResource Conv}, Mode=OneWay}"/> 
       </Style> 
      </DataGrid.CellStyle>    
     </DataGrid> 
    </StackPanel> 
</Window>