为什么此代码不起作用
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>
<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>
错误:
无法将类型为“System.Data.DataRowView”的对象强制转换为类型 'BooksManagement_Version1.Product'。
答案 0 :(得分:0)
似乎Row的DataContext不是您所期望的。检查您是否绑定了Product
的集合。此外,如果您可以发布有用的DataGrid
的xaml。