[英]C# WPF Data grid display error: Object being displayed
我已分配要在 WPF 數據網格中顯示的報告列表。
作為報告 object 的屬性的所有值都顯示正常,但是報告構造函數中包含的對象的值僅顯示來自數據網格的通用 object 名稱,我不確定如何從所述對象訪問任何基礎屬性為用戶提供更有意義的顯示。
報告構造函數:
public Report(string reporterName, Asset asset, Location incidentLocation, Room room, string incidentType)
{
ReporterName = reporterName;
Asset = asset;
IncidentLocation = incidentLocation;
Room = room;
IncidentType = incidentType;
}
數據網格 XAML:
<DataGrid Name="ReportsGrid" HorizontalAlignment="Left" Height="212" Margin="33,252,0,0" VerticalAlignment="Top" Width="725"/>
使用報表 object 列表設置數據網格:
List<Report> reports = new List<Report>();
reports.Add(report);
ReportsGrid.ItemsSource = reports;
任何幫助或建議將不勝感激。 謝謝你的時間。
自動生成列時,它們將顯示 object 的ToString
方法的結果,因為無法知道如何顯示自定義類型的實例。
如果您可以手動創建列,則可以為已經存在的列類型(如DataGridTextColumn
)指定屬性路徑。 假設Asset
有一個名為Name
的字符串屬性。
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Reports}">
<DataGrid.Columns>
<DataGridTextColumn Header="Asset" Binding="{Binding Asset.Name}"/>
<!-- ...other columns -->
</DataGrid.Columns>
</DataGrid>
如果您的數據類型更復雜,您可以改為使用DataGridTemplateColumn
並創建自定義數據模板以進行顯示和編輯。
<DataGridTemplateColumn Header="Asset">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate DataType="{x:Type local:Report}">
<TextBlock Text="{Binding Asset.Name}"/>
<!-- ...other controls -->
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate DataType="{x:Type local:Report}">
<TextBox Text="{Binding Asset.Name}"/>
<!-- ...other controls -->
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
如果您絕對需要自動生成列,則需要在代碼隱藏或自定義行為中掛鈎AutoGeneratingColumn
事件。
<DataGrid x:Name="MyDatagrid" ItemsSource="{Binding Reports}">
MyDatagrid.AutoGeneratingColumn += OnAutoGeneratingColumns;
然后更改自動生成的列,甚至替換它們。 在下面的示例中,我替換了一個列,但您也可以只使用已經生成的e.Column
,例如DataGridTextColumn
並在代碼中的Binding
屬性中設置綁定,就像在上面的示例中手動生成的列一樣。
private void OnAutoGeneratingColumns(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.Column.Header.Equals("Asset"))
{
// Create a new template column
var templateColumn = new DataGridTemplateColumn
{
Header = e.PropertyName,
// ...set other properties
};
// Create a data template (or get one from a resource dictionary)
var template = new DataTemplate(typeof(Report));
// ...populate the data template and set bindings if needed
// Set the cell template
templateColumn.CellTemplate = template;
// Do the same as above for the editing template if needed
templateColumn.CellEditingTemplate = template;
// Overwrite the auto-generated column
e.Column = templateColumn;
}
// ...handle other columns or leave them as they are
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.