在您的XAML來DataGrid綁定到某一類具有的屬性對象的ObservableCollection。
XAML:
<WpfToolkit:DataGrid
x:Name="MyDataGrid"
ItemsSource="{Binding Path=Collection}"
HorizontalScrollBarVisibility="Hidden" SelectionMode="Extended"
CanUserAddRows="False" CanUserDeleteRows="False"
CanUserResizeRows="False" CanUserSortColumns="False"
AutoGenerateColumns="False"
RowHeaderWidth="25" RowHeight="25"/>
接下來,您可以在C#/ VBA編程方式創建列和每一列綁定到類,其中的ObservableCollection,包含了對象的屬性。通過添加類的對象,您將向數據網格添加行。換句話說,ObservableCollection中類的每個對象都是一行,並且該類的屬性將成爲列。
下面是一個例子,如何通過編程綁定你列... C#:
ObservableCollection<IData> datagridData = new ObservableCollection<IData>();
Binding items = new Binding();
PropertyPath path = new PropertyPath("Name"); // 'Name' is actually the name of the variable representing the property
items.Path = path;
MyDataGrid.Columns.Add(new DataGridTextColumn()
{
Header = "Names",
Width = 275,
Binding = items
});
//repeat the creation of columns
//...
//- Add some objects to the ObservableCollection
//- Then bind the ItemsSource of the datagrid to the ObservableCollection
datagridData .Add(new Data("Bob", string.Empty));
MyDataGrid.DataContext = new DataModel{ MyData = datagridData };
*編輯: 對此深感抱歉!這裏是你如何能完全實現同樣的事情在XAML:
<WpfToolkit:DataGrid
x:Name="MyDataGrid"
ItemsSource="{Binding Path=Collection}"
HorizontalScrollBarVisibility="Hidden" SelectionMode="Extended"
CanUserAddRows="False" CanUserDeleteRows="False"
CanUserResizeRows="False" CanUserSortColumns="False"
AutoGenerateColumns="False"
RowHeaderWidth="25" RowHeight="25">
<WpfToolkit:DataGridTextColumn
Header="Names" Width="2*"
Binding="{Binding Path=Name}"/>
<WpfToolkit:DataGridTextColumn
Header="Names" Width="2*"
Binding="{Binding Path=Age}"/>
</WpfToolkit:DataGrid.Columns>
</WpfToolkit:DataGrid>
編輯2:這裏是的ObservableCollection和類的代碼可能看起來像在C#:
public class DataModel
{
public ObservableCollection<IData> MyData{ get; set; }
}
public interface IData
{
string Name{ get; set; }
string Age{ get; set; }
}
public class Data : IData
{
public Data(string name, string age)
{
Name= name;
Age= age;
}
public string Name{ get; set; }
public string Age{ get; set; }
}
我想這是唯一的方法,我會保持打開一段時間的問題,也許有人會想出一些東西,否則接受這一點。 只是一個旁註:網格能夠自動生成額外的列(AutoGenerateColumns屬性)。但這當然不起作用或列表。問題是,整個綁定是否可以與匿名類一起工作?或者更好 - 是否使用反射來生成額外的列?我可以爲數據創建一個動態類,但在可維護性和可讀性方面可能會更糟...... – 2009-12-08 14:39:55
我知道這並不理想...... MV-VM發展得如此巨大,因爲此控件最初是作者創作的,我相信將來會有一個版本將列作爲DP進行公開。在此之前,我想我們必須選擇最實用的解決方案....乾杯, – kiwipom 2009-12-08 17:29:09
我知道這是舊的,但我已經注意到,取決於操作系統(也許是否安裝.Net 4.5,即使在目標.Net 4.0),設置AutoGenerateColumns = true確實在Windows 7中使用反射。因此,您可以返回一個IEnumerable