24

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

4

3 に答える 3

39

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);
于 2009-12-05T01:14:17.383 に答える
10

Uはこれを試すことができます

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);
于 2011-04-28T04:51:28.370 に答える
1

重要: 条件またはその他のスタイルによって色付けされていない行には、必ずデフォルトを割り当ててください。

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

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

于 2010-01-17T02:52:35.687 に答える