2017-08-23 10 views
0

GridView内のすべてのセルにコンバーターを接続して、テキストの内容に応じて色を変更できる方法はありますか?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> 
関連する問題