如何在代码中进行绑定?

时间:2010-09-29 13:42:23

标签: c# wpf

<Custom:DataGrid Grid.Row="1" Background="{x:Null}" x:Name="datagrid" 
                                 DataContext="{StaticResource dataSetPartner}" 
                                 ItemsSource="{Binding Partner}"....

<ObjectDataProvider x:Key="dataSetPartner" MethodName="PartnerStat" ObjectType="{x:Type loc:DataSetCreator}"  />

这是一项很棒的工作,但我需要编写代码......

我的代码不起作用:

adatagrid.DataContext = null;
datagrid.DataContext = this.Resources["dataSetPartner"];

Binding b = new Binding("DataContext");
b.Source = datagrid;
b.Path = new PropertyPath("Partner");
b.Mode = BindingMode.OneWay;
datagrid.SetBinding(DataGrid.ItemsSourceProperty, b);

为什么?

1 个答案:

答案 0 :(得分:2)

ObjectDataProvider在XAML中用于指示数据源。您指定要调用的类型和方法。但是,您无需在代码中使用ObjectDataProvider,因为您可以直接调用该方法。


  var dsc = new DataSetCreator();
  this.DataContext = dsc.PartnerStat();
  // bind a textblock
  Binding b = new Binding("FirstName");
  textBlock1.SetBinding(TextBlock.TextProperty, b);
  // bind the datagrid
  // don't specify a path, it will bind to the entire collection

  var b1 = new Binding(); 
  dataGrid1.SetBinding(DataGrid.ItemsSourceProperty, b1);