Why this code does not work
private void dataGrid_LoadingRow(object sender, Microsoft.Windows.Controls.DataGridRowEventArgs e)
{
//Highlighting rows
Product product = (Product)e.Row.DataContext;
if (product.Price > 100)
{
e.Row.Background = highlightBrush;
}
else
{
e.Row.Background = normalBrush;
}
}
}
class Product
{
public int IdBook ;
public string NameBook;
public string Author;
public string Description;
public string DateRegister;
public Int32 Price;
}
xaml:
<dg:DataGrid Name="dataGrid" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" IsReadOnly="True"
HeadersVisibility="Column" SelectedIndex="-1" Margin="0,315,0,25" Background="#FF484040" BorderBrush="#FF484040"
SelectionChanged="dataGrid_SelectionChanged" LoadingRow="dataGrid_LoadingRow">
<dg:DataGrid.Columns>
<dg:DataGridTextColumn Binding="{Binding IdBook}" Header="IdBook" ></dg:DataGridTextColumn>
<dg:DataGridTextColumn Binding="{Binding NameBook}" Header="NameBook"></dg:DataGridTextColumn>
<dg:DataGridTextColumn Binding="{Binding Author}" Header="Author"></dg:DataGridTextColumn>
<dg:DataGridTextColumn Binding="{Binding Price}" Header="Price"></dg:DataGridTextColumn>
<dg:DataGridTextColumn Binding="{Binding DateRegister}" Header="DateRegister"></dg:DataGridTextColumn>
<dg:DataGridTextColumn Binding="{Binding Description}" Header=Description" Width="*"></dg:DataGridTextColumn>
<dg:DataGridTemplateColumn>
<dg:DataGridTemplateColumn.CellTemplate>
开发者_C百科 <DataTemplate>
<Button Click="Delete_Click" ToolTip="Delete" Height="30" Width="30" FlowDirection="RightToLeft" Style="{DynamicResource GlassButton}"
Background="{DynamicResource TileBrush}">
</Button>
</DataTemplate>
</dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>
<dg:DataGridTemplateColumn Width="15" >
<dg:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox ToolTip="Select" Name="Checkbox" Height="15" Width="15" HorizontalContentAlignment="Center" HorizontalAlignment="Center"
VerticalAlignment="Center" VerticalContentAlignment="Center">
</CheckBox>
</DataTemplate>
</dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>
</dg:DataGrid.Columns>
</dg:DataGrid>
error :
Unable to cast object of type 'System.Data.DataRowView' to type 'BooksManagement_Version1.Product'.
It seems that the DataContext of the Row is not what you are expecting. Check that you are binding to a collection of Product
. Also, if you can post the xaml for the DataGrid
that would be helpful.
精彩评论