1
votes

I'm extending a control to be able to reuse it across my current Xamarin project. As part of this control, I need to create a DataTemplate programmatically. I have this part figured out and it works ok.

The DataTemplate has a Label in it. I need to bind the Label's BindingContext property to {Binding Source}. I need to bind the Label's Text property to {Binding Path=Name}.

This works in XAML, but I don't want to have to copy it to a million different places in the code base.

<dxGrid:TemplateColumn FieldName="MyPropertyName"
                    Caption="MyColumn">
<dxGrid:TemplateColumn.DisplayTemplate>
    <DataTemplate>
        <Label BindingContext="{Binding Source}"
                Text="{Binding Source, Path=MyPropertyName}" />
    </DataTemplate>
</dxGrid:TemplateColumn.DisplayTemplate>

My extended control looks like this right now:

public class MyColumn : TemplateColumn
{
    public MyColumn()
    {
        DataTemplate displayTemplate = new DataTemplate(() =>
        {
            BindingBase textBinding = new Binding(FieldName);

            Label label = new Label();

            // TODO: Bind BindingContextProperty to {Binding Source}
            //label.SetBinding(BindingContextProperty, binding);

            label.SetBinding(Label.TextProperty, textBinding);
            return new ViewCell
            {
                View = label
            };
        });

        DisplayTemplate = displayTemplate;
    }
}

I'm getting hung up in the binding because I'm not sure how to do the equivalent of {Binding Source} in code. Any help would be appreciated.

2

2 Answers

1
votes

@Eugene - Thanks for the response. Unfortunately this does not work and binding to "Source" like that throws a Null Reference Exception. I made another pass at it this morning and got it working this way:

public MyColumn()
{
    DataTemplate displayTemplate = new DataTemplate(() =>
    {
        Grid grid = new Grid();
        grid.SetBinding(Grid.BindingContextProperty, "Source");

        Label label = new Label();
        label.SetBinding(Label.TextProperty,FieldName);

        grid.Children.Add(label);

        return grid;
    });

    this.DisplayTemplate = displayTemplate;
}
0
votes

It's simple, use name of property

label.SetBinding(BindingContextProperty, "Source");