使用绑定在代码后面创建DataGrid

时间:2014-01-10 09:01:16

标签: c# wpf xaml datagrid

这是在XAML中的DataGrid中:

ItemsSource="{Binding Path=NewContactList,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" ItemsPanel="{StaticResource panelTemplate}" 
ItemTemplate="{StaticResource ListTemplate}" 
DragDrop:DragDropHelper.IsDragSource="true" 
DragDrop:DragDropHelper.IsDropTarget="true" 
DragDrop:DragDropHelper.DragDropTemplate="{StaticResource DragTemplate}"

我想在Codebehind中创建DataGrid,但我知道如何设置Bindings和我的DragDrop:DragDropHelper

有人能帮帮我吗?

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

Dim dataGridObj As New DataGrid()

Dim itemsSourceBinding As New Binding("NewContactList")
itemsSourceBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
itemsSourceBinding.Mode = BindingMode.TwoWay

Dim itemsPanelResource = Me.FindResource("panelTemplate")
Dim itemTemplateResource = Me.FindResource("ListTemplate")
Dim dragDropTemplate = Me.FindResource("DragTemplate")

dataGridObj.SetBinding(ListBox.ItemsSourceProperty, itemsSourceBinding)
dataGridObj.ItemsPanel = CType(itemsPanelResource, ItemsPanelTemplate)
dataGridObj.ItemTemplate = CType(itemTemplateResource, DataTemplate)
dataGridObj.SetValue(DragDropHelper.IsDragSource, True)
dataGridObj.SetValue(DragDropHelper.IsDropTarget, True)
dataGridObj.SetValue(DragDropHelper.DragDropTemplate, CType(dragDropTemplate, DataTemplate))

答案 1 :(得分:1)

试试这个:

var myDataGrid = new DataGrid();
myDataGrid.SetBinding(DataGrid.ItemsSourceProperty, new Binding("NewContactList") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Mode = BindingMode.TwoWay });
myDataGrid.SetResourceReference(DataGrid.ItemsPanelProperty, "panelTemplate");
myDataGrid.SetResourceReference(DataGrid.ItemTemplateProperty, "ListTemplate");
myDataGrid.SetValue(DragDropHelper.IsDragSourceProperty, True);
myDataGrid.SetValue(DragDropHelper.IsDropTargetProperty, True);
myDataGrid.SetResourceReference(DragDropHelper.DragDropTemplateProperty, "DragTemplate");