[英]How to bind to concrete objects in a DataGrid/DataTable
編輯:這些列僅在運行時才知道,這就是為什么我要動態地在DataTable中構造數據的原因。
我有一些動態數據,必須在DataGrid中顯示。 數據網格中的每個單元都將綁定到復雜的數據類型。 我成功構造了DataTable並將其綁定到它。 DataGrid可以正確自動生成其列,但是所有數據都是字符串。
在后面的代碼中(用於臨時調試),我正在處理AutoGeneratingColumn事件,並嘗試動態設置列類型。 如果具有復雜類型:
public class BoolData
{
public bool Value { get; set; }
public Guid Id{ get; set; }
}
在View的背后代碼中,我這樣做:
private void DataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyType == typeof(string))
{
var col = new DataGridTextColumn {Binding = new Binding(e.PropertyName)};
e.Column = col;
e.Column.Header = e.PropertyName;
}
else if (e.PropertyType == typeof(BoolData))
{
var col = new DataGridCheckBoxColumn {Binding = new Binding(e.PropertyName + "." + "Value")};
e.Column = col;
e.Column.Header = e.PropertyName;
}
}
問題是,即使我將MyBool對象添加到DataTable中,字符串“ MyNamespace.MBoolData”也是DataGrid中的內容,這意味着第一個“ if”子句是唯一使用的子句。 就像DataGrid或DataTable在嘗試顯示對象之前在對象上調用ToString()一樣。
所以我想我的問題是-如何創建一個包含復雜對象的動態DataTable,然后綁定到它。
您只需要在XAML中定義列,並使用DataGridTemplateColumn
定義復雜對象的外觀即可。 鏈接頁面上有完整的代碼示例,但這是基礎知識。您定義DataTemplate
來確切描述UI中復雜對象的外觀,然后可以將其設置為DataGridTemplateColumn.CellTemplate
的值。屬性。
您應該直接在XAML中嘗試此操作。
<DataGrid ItemsSource="{Binding YourDataSource}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="TheHeaderNameOfYourColumn" Width="SizeToCells">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Value}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
在不知道列名的情況下,應該在DataGrid資源中創建一個模板
<DataGrid>
<DataGrid.Resources>
<DataTemplate DataType="{x:Type my:BoolData}"> <!--where "my" points to the correct namespace-->
<CheckBox IsChecked="{Binding Value}"/>
</DataTemplate>
</DataGrid.Resources>
</DataGrid>
好的,我知道了問題所在。 如果我粘貼了用於創建DataTable的代碼,則可能會發現它。
創建數據表(特別是數據列)時,必須顯式設置數據類型,否則默認為字符串。 一點也不明顯,但是終於讓它起作用了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.