我正在从数据库中检索数据并将内容放入WPF DataGrid中,如此;
命名空间ContractsExcel { public partial class UserSelection:Page { public UserSelection() { 的InitializeComponent(); dataGrid.CanUserAddRows = false; string username = Environment.UserName; userImage.Source = new BitmapImage(new Uri(@“C:\ Users \ DanD \ Desktop \”+ username +“。jpg”)); }
private void FillDataGrid(object sender, RoutedEventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["dbfString"].ConnectionString;
using (OleDbConnection dbfCon = new OleDbConnection(constr))
{
try
{
dbfCon.Open();
DataTable dTable = new DataTable();
string dbfQuery = "SELECT em_pplid, em_name, em_netname FROM employs WHERE em_netname NOT LIKE ''";
OleDbCommand MyQuery = new OleDbCommand(dbfQuery, dbfCon);
OleDbDataAdapter DA = new OleDbDataAdapter(MyQuery);
DA.Fill(dTable);
dataGrid.ItemsSource = dTable.AsDataView();
}
catch (OleDbException)
{
throw;
}
}
}
}
}
我想要做的是根据行单元格的内容更改整行的字体颜色,例如,如果珍惜订单,请将行的字体颜色更改为红色。
虽然现在存在关于此主题的多个问题,但我找不到任何特定的内容。这是否需要通过XAML或C#完成,以及我如何实现此功能?
使用XAML更新代码;
<DataGrid x:Name="dataGrid" Margin="0,0,10,0" Grid.ColumnSpan="3" ColumnWidth="*" FontSize="18.667">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding em_netname}" Value='Chris'>
<Setter Property="Foreground" Value="Red"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
用C#填充DataContext的代码;
命名空间ContractsExcel { public partial class UserSelection:Page { public UserSelection() { 的InitializeComponent(); dataGrid.CanUserAddRows = false; string username = Environment.UserName; userImage.Source = new BitmapImage(new Uri(@“C:\ Users \ DanD \ Desktop \”+ username +“。jpg”)); }
private void FillDataGrid(object sender, RoutedEventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["dbfString"].ConnectionString;
using (OleDbConnection dbfCon = new OleDbConnection(constr))
{
try
{
dbfCon.Open();
DataTable dTable = new DataTable();
string dbfQuery = "SELECT em_pplid, em_name, em_netname FROM employs WHERE em_netname NOT LIKE ''";
OleDbCommand MyQuery = new OleDbCommand(dbfQuery, dbfCon);
OleDbDataAdapter DA = new OleDbDataAdapter(MyQuery);
DA.Fill(dTable);
dataGrid.ItemsSource = dTable.AsDataView();
}
catch (OleDbException)
{
throw;
}
}
}
}
}
答案 0 :(得分:-1)
使用行的自定义颜色为数据网格编写数据模板。 您将数据表直接分配给网格。这样您就无法根据数据更改颜色。 否则你必须为颜色编写模型类,然后才能根据数据设置颜色。