Need help about datagrid
i have datagrid(see bellow) there is columns with date time how i can make background red where rooomNumer is 777 from 1/8/2011 to 5/8/2011 with code behind? Room number column bind with observable collection
ObservableCollection<RoomsInfoData> _RoomsInfoCollection = new ObservableCollection<RoomsInfoData>();
public RoomsInfo()
public ObservableCollection<RoomsInfoData> RoomsInfoCollection
{
get { return _RoomsInfoCollection; }
}
public class RoomsInfoData
{
public string RoomType { get; set; }
public string RoomNumber { get; set; }
public string RoomStatus { get; set; }
}
HProDataContext db = new HProDataContext();
var _RoomNumber = (from d in db.SelectRooms select d.roomnumber).ToList();
var _RoomType = (from d in db.SelectRooms select d.roo开发者_开发知识库mtype).ToList();
var _RoomStatus = (from d in db.SelectRooms select d.status).ToList();
for (int i = 0; i < _RoomNumber.Count; i++)
{
_RoomsInfoCollection.Add(new RoomsInfoData { RoomNumber = _RoomNumber[i], RoomType = _RoomType[i], RoomStatus = _RoomStatus[i] });
}
Assuming that
- "this" refers to your window or user control in which this data grid is placed.
- this.dataGrid refers to your datagrid in which you have added columns from code behind.
We will specify a style in the Window / UserControl's Resources collection ... like this
<UserControl.Resources> <!-- could be Window.Resources if datagrid lies in a Window -->
<Style x:Key="RoomNumberValidationCellStyle"
TargetType="{x:Type DataGridCell}"> <!-- DataGridCell because we need to apply this style to specific columns -->
<Style.Triggers>
<DataTrigger Binding="{Binding Path=RoomNumber}" Value="777">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
in code behind after you set all columns to this.dataGrid ... do this...
foreach(var col in this.dataGrid.Columns)
{
var headerText = (string)col.Header;
if (headerText == "1/8/2011" || headerText.Header == "2/8/2011"
|| headerText.Header == "3/8/2011" || headerText.Header == "4/8/2011"
|| headerText.Header == "5/8/2011")
col.CellStyle = this.FindResource("RoomNumberValidationCellStyle") as Style;
}
Let me know if this helps.
<Style x:Key="RedRowStyle" TargetType="{x:Type dg:DataGridRow}">
<Setter Property="Background" Value="Red"/>
<Style.Triggers>
<DataTrigger Binding="{Binding PropertyName}" Value="777" >
<Setter Property="Background" Value="DarkGray" />
<Setter Property="Foreground" Value="White" />
</DataTrigger>
</Style.Triggers>
</Style>
Just replace PropertyName with the property in the ViewModel where the value will be 777 and apply to the proper rows.
精彩评论