SQLを使用して動的に作成されるDataTableに複数のDataGridがバインドされています。 DataTableレコードが変更(追加、変更、削除)されるたびに、DataGridCellsは背景色を変更します(緑=新、黄=変更など)。WPF:実行時にDataGridセル/行の背景色を動的に変更します。
私は(コードは非常に単純化されている)_RowPostPaintを使用してのDataGridViewの背景色を変更WinFormsので:
private void DataGridViewTest_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
DataRow row = (this.Rows[e.RowIndex].DataBoundItem as DataRowView).Row;
switch (row.RowState)
{
case DataRowState.Added:
myBitmap = new Bitmap(imageList.Images[1]);
this[0, e.RowIndex].Style.BackColor = CellChangesColorAdded;
break;
case DataRowState.Modified:
string sValOld = row[0, DataRowVersion.Original].ToString();
string sValNew = row[0].ToString();
if (sValOld != sValNew)
{
this[0, e.RowIndex].Style.BackColor = CellChangesColorMod;
}
break;
case DataRowState.Deleted:
this[0, e.RowIndex].Style.BackColor = CellChangesColorDel;
break;
}
}
私は、彼らが実行時に作成され、私が持っているようcountless examples like thisのようにXAMLで列の依存関係をハードコーディングする必要はありません使用中の多くのDataGrid。
<Window.Resources>
<Style x:Key="MyStyle" TargetType="{x:Type DataGridCell}">
<Setter Property="Background" Value="Green" />
</Style>
</Window.Resources>
<DataGrid x:Name="dataGrid" Grid.Row="4" Grid.ColumnSpan="6"
ItemsSource="{Binding}"
>
</DataGrid>
は.cs:それは等:
XAMLソート時に変更を保持しないよう、DataGrid_CellEditEndingに障害が発生した使用しようと
は
dataGrid.DataContext = dataTable.DefaultView; // Table filled by SQL query
dataGrid.CellEditEnding += dataGrid_CellEditEnding;
// Problem: Color changes disappear when user sorts DataGrid
private void dataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if (e.EditAction == DataGridEditAction.Commit)
{
TextBox tb = e.EditingElement as TextBox;
DataGridCell cell = tb.Parent as DataGridCell;
// evaluate row changes and change color accordingly
//cell.Background = new SolidColorBrush(Colors.Yellow); // set style instead of color
cell.Style = (Style)this.Resources["MyStyle"]; // color is changed to green, according to defined style
}
}
これは、背景色を変更します完全に細かいですが、スタイルはDataGridなどのソート時に保持されません。
色の変更を維持する方法を教えてください。私の意見では、DataRowをヘルパクラスにバインドし、DataTableの変更時にそれぞれのスタイルを返すのが最善の解決策です。しかし、私はまだその例を見ていません。完全のために
私はそれが厳しいと思う。私は 'dataTable.DefaultView'をセルの現在の状態を管理するヘルパークラスにラップすることなく、この動作を見ることができません。私の推測では、DataGridを並べ替えると描画されたすべてのセルが更新され、特定のセルを描画する方法を知っているのはDataGridだけなので、忘れてしまったと思います。 DataGridは、各セルを色付けする方法をデータ_から知る必要があります。 –
@MarkusHütterええ、私も思ったことだと私は基本的に特定のクラスまたはハードコードされたXAMLのヘルパークラスを使用する方法を知っています。私は私の問題を扱っている例は見ていないし、バインドされたDataTableのヘルパークラスの使い方を理解していない。 – ray