我正在使用中继器控件。我的项目属性之一是布尔值。我知道我可以在 Text 属性中做一个条件语句,例如:
Text='<%# Item.Boolean ? "Text 1" : "Text 2" %>
但是,如果我想要相同的文本但不同的 CSS 样式取决于布尔值怎么办?
像下面这样的代码可能吗?
CssClass=<%# Item.Boolean ? "CssClass1" : "CssClass2" %>
你不能那样做。不是 runat 服务器类型的标签,因此它无法尝试在那里执行逻辑。相反,您需要在 Page_PreRenderComplete 中设置 gridview 的属性。
使用类似下面的东西来做到这一点:
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
this.FormatGridviewRows();
}
private void FormatGridviewRows()
{
foreach (GridViewRow row in this.GridView1.Rows)
{
// Don't attempt changes on header / select / etc. Only Datarow
if (row.RowType != DataControlRowType.DataRow) continue;
// At least make sure everything has the default class
row.CssClass = "gridViewRow";
// Don't affect the first row
if (row.DataItemIndex <= 0) continue;
if (row.RowState == DataControlRowState.Normal || row.RowState == (DataControlRowState.Normal ^ DataControlRowState.Edit))
{
row.CssClass = !this.cbForceOverride.Checked
? "gridViewRow"
: "gridViewRow gridViewRowDisabled";
}
if (row.RowState == DataControlRowState.Alternate || row.RowState == (DataControlRowState.Alternate ^ DataControlRowState.Edit))
{
row.CssClass = !this.cbForceOverride.Checked
? "gridViewAltRow"
: "gridViewAltRow gridViewAltRowDisabled";
}
}
}
然后在您的样式表中:
.gridViewRow {
background-color: #f2f2f2;
}
.gridViewAltRow {
background-color: #ffffff;
}
.gridViewRow, .gridViewAltRow {
color: #000000;
}
.gridViewRowDisabled, .gridViewAltRowDisabled {
color: #DDDDDD;
}