web-dev-qa-db-ja.com

プログラムによってDataGridの行に色を割り当てる

実行時にDataTableに追加する行に色を割り当てる必要があります。これはどのように行うことができますか?

21
Abdul Khaliq

DataGridのLoadingRowイベントを処理して、行が追加されていることを検出できます。イベントハンドラーでは、ItemsSourceとして機能するDataTableに追加されたDataRowへの参照を取得できます。次に、DataGridRowの色を好きなように更新できます。

void dataGrid_LoadingRow(object sender, Microsoft.Windows.Controls.DataGridRowEventArgs e)
{
    // Get the DataRow corresponding to the DataGridRow that is loading.
    DataRowView item = e.Row.Item as DataRowView;
    if (item != null)
    {
        DataRow row = item.Row;

            // Access cell values values if needed...
            // var colValue = row["ColumnName1]";
            // var colValue2 = row["ColumName2]";

        // Set the background color of the DataGrid row based on whatever data you like from 
        // the row.
        e.Row.Background = new SolidColorBrush(Colors.BlanchedAlmond);
    }           
}

XAMLでイベントにサインアップするには:

<toolkit:DataGrid x:Name="dataGrid"
    ...
    LoadingRow="dataGrid_LoadingRow">

またはC#で:

this.dataGrid.LoadingRow += new EventHandler<Microsoft.Windows.Controls.DataGridRowEventArgs>(dataGrid_LoadingRow);
37
Jeremy

あなたはこれを試すことができます

XAMLで

<Window.Resources>
<Style TargetType="{x:Type DataGridRow}">
    <Style.Setters>
        <Setter Property="Background" Value="{Binding Path=StatusColor}"></Setter>
    </Style.Setters>            
</Style>
</Window.Resources>

データグリッド内

<DataGrid AutoGenerateColumns="False" CanUserAddRows="False" Name="dtgTestColor" ItemsSource="{Binding}" >
<DataGrid.Columns>                            
    <DataGridTextColumn Header="Valor" Binding="{Binding Path=Valor}"/>
</DataGrid.Columns>
</DataGrid>

コードで私はクラスを持っています

public class ColorRenglon
{
    public string Valor { get; set; }
    public string StatusColor { get; set; }
}

DataContextを設定するとき

dtgTestColor.DataContext = ColorRenglon;
dtgTestColor.Items.Refresh();

行の色を設定しない場合、デフォルト値は灰色です

あなたはこのサンプルでこのサンプルを試すことができます

List<ColorRenglon> test = new List<ColorRenglon>();
ColorRenglon cambiandoColor = new ColorRenglon();
cambiandoColor.Valor = "Aqui va un color"; 
cambiandoColor.StatusColor = "Red";
test.Add(cambiandoColor);
cambiandoColor = new ColorRenglon();
cambiandoColor.Valor = "Aqui va otro color"; 
cambiandoColor.StatusColor = "PaleGreen";
test.Add(cambiandoColor);
10
DarKainSoul

[〜#〜]重要[〜#〜]:条件によって色付けされていない行またはその他の行には常にデフォルトを割り当てるようにしてください他のスタイル。

C#Silverlight Datagrid-Row Color Change に対する私の回答を参照してください。

PS。 Silverlightを使用していて、WPFでこの動作を確認していません

1
Simon_Weaver