C# – WPF DataGrid binding problem

bindingcwpfxaml

Lets say we have the following code in XAML (the datagrid is bound to an ObservableCollection and the column to a property of the ObservableCollection:

<WpfToolkit:DataGrid
        ItemsSource="{Binding Path=Collection}"
        HorizontalScrollBarVisibility="Hidden" SelectionMode="Extended"
        CanUserAddRows="False" CanUserDeleteRows="False"
        CanUserResizeRows="False" CanUserSortColumns="False"
        AutoGenerateColumns="False"
        RowHeaderWidth="17" RowHeight="25">
        <WpfToolkit:DataGrid.Columns>

            <WpfToolkit:DataGridTextColumn
                Header="Names" Width="2*"
                Binding="{Binding Path=Name}"/>

        </WpfToolkit:DataGrid.Columns>
</WpfToolkit:DataGrid>

How can you create a new column programmatically in C# with the binding set to a certain PropertyPath (in my case a property of an ObservableCollection)?

This is what I have right now:

Binding items = new Binding();
PropertyPath path = new PropertyPath("Name");
items.Path = path;



MyDataGrid.Columns.Add(new DataGridTextColumn()
{
   Header = "Names",
   Width =  275,
   Binding = items
});

I am pretty sure that the problem is in the PropertyPath but I do not know what I must write in it…

Thank you for any help!

Best Answer

I have almost the exact same code as you, I just create the binding in a slightly different way:

void Add(ColumnViewModel columnViewModel)
{
    var column = new DataGridTextColumn
    {
        Header = columnViewModel.Name,
        Binding = new Binding("[" + columnViewModel.Name + "]")
    };
    dataGrid.Columns.Add(column);
}
Related Topic