Mediator
Mediator

Reputation: 15378

How to make a Binding in code?

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

and

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

this is great work, but I need to write a code...

my code not is work:

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);

why?

Upvotes: 0

Views: 1818

Answers (1)

Walt Ritscher
Walt Ritscher

Reputation: 7037

The ObjectDataProvider is used in XAML to indicate a data source. You specify the type and the method to call. There's no need to use the ObjectDataProvider in your code however, because you can call the method directly.


  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);

Upvotes: 2

Related Questions