Reputation: 21
I need to add columns to silverlight columns at runtime and also perform the bindings for the columns.
This is how i do it statically in xaml
<sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="CriteriaName" Width="2*" Binding="{Binding Path=[CriteriaName]}" IsReadOnly="True" />
Now i want do the same in code behind,
here is what i have done
foreach(string Col in lColumnNames)
{
DataGridTextColumn DGCol=new DataGridTextColumn();
DGCol.Header= Col;
Binding lObjBinding = new Binding(Col);
lObjBinding.Mode = BindingMode.OneWay;
DGCol.Binding = lObjBinding;
GrdQuickFindResult.Columns.Add(DGCol);
}
This is not working.All i can see are blank rows in the DataGrid,as if the binding hasn't happened. Pls check and tell me if all the things that i have done using xaml is done using C# as well or is there some property that is left to be set in the Binding Object that i have created. Thanx
Upvotes: 0
Views: 716
Reputation: 7058
A binding like:
"{Binding Path=MyProperty}"
is just a verbose way of writing:
"{Binding MyProperty}"
In the same way that
Binding b = new Binding();
is the same as
Binding b = new Binding("MyProperty");
And means that you are binding the text of your TextBoxColumn to the value of the property "MyProperty" in the data object which will be set as DataContext of a row in your DataGrid. For this we are assuming your data object is something like:
public class DataObject{
public object MyProperty {get; set;}
}
If your data objects are like that, your bindings in code behind are fine and they should work.
When you especify a binding like:
"{Binding Path=[MyProperty]}"
Or
"{Binding [MyProperty]}"
You are binding the the indexer of the data object (if it implements one) and acessing the value corresponding to the the index "MyProperty". If you do this, I assume your data object is a IDictionary or a class which implements a indexer, like:
public class DataObject{
public object this[object index]
{
get{ /*return something*/ }
set { /*set something*/ }
}
}
Just a suggestion: use camel case for your local variables, it looks strange for other people looking at your code, seems they are instance properties or static fields.
Upvotes: 1
Reputation: 21
foreach(string Col in lColumnNames)
{
DataGridTextColumn DGCol=new DataGridTextColumn();
DGCol.Header= Col;
Binding lObjBinding = new Binding();
lObjBinding.Mode = BindingMode.OneWay;
//=====This is what was missing======================//
lObjBinding.Path = new PropertyPath("["+Col+"]");
//==================================================//
DGCol.Binding = lObjBinding;
GrdQuickFindResult.Columns.Add(DGCol);
}
Upvotes: 0