在此处输入代码我将从Data对象中的属性不会显示在Datagrid上。
我期望列类别中的字符串,该字符串在此项目的XAML中定义。 “Id”和“描述”已在DataGrid上成功显示,但“类别”未成功显示。见下面的截图。
<Grid>
<DataGrid Name="view" AutoGenerateColumns="False" Margin="-4,0,4,0" >
<DataGrid.Columns>
<DataGridTextColumn Header="#" Binding="{Binding Id}" />
<DataGridTemplateColumn Header="Category">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Label Content="{Binding Category.Name}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Description">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Label Content="{Binding Beschreibung}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
public MainWindow()
{
DataContext = this;
InitializeComponent();
Start();
}
public void Start()
{
var payments = new List<Payment>();
using (var dc = new DataContext())
{
payments = (from c in dc.Categories
join p in dc.Payments
on c.Id equals p.CategoryId
select p).ToList();
}
view.ItemsSource = payments;
}
}
这是我的付款类
public partial class Payment
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[Required]
[StringLength(500)]
public string Beschreibung { get; set; }
public DateTime Datum { get; set; }
public int Amount { get; set; }
public int IsIncome { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
这是我的类别课程
public partial class Category
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Category()
{
Payments = new HashSet<Payment>();
}
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[Required]
[StringLength(500)]
public string Name { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Payment> Payments { get; set; }
}
尝试更改此代码
payments = (from c in dc.Categories
join p in dc.Payments
on c.Id equals p.CategoryId
select p)
.ToList();
至
payments = (from c in dc.Categories
join p in dc.Payments
on c.Id equals p.CategoryId
select p)
.Include("Category")
.ToList();
它将急切地从数据库加载Category
,它应该解决你的问题。