0
votes

I'm trying to create a common custom control in the XamarinForms PCL project that would be the equivalent of a UserControl in Windows 8/RT.

Here's what I have so far.

First I created the bindable property in the control that inherits from ContentView:

public static readonly BindableProperty TitleProperty =
        BindableProperty.Create<MyCustomControl, string> (
            p => p.Title, defaultValue: "NO TITLE", defaultBindingMode: BindingMode.TwoWay,
            validateValue: null,
            propertyChanged: (bindableObject, oldValue, newValue) =>
            {
                if (bindableObject != null)
                {

                }
                Logger.Instance.WriteLine ("TITLE PROPERTY CHANGED: OldValue = " + oldValue + " , NewValue = " + newValue);
            });

    public string Title { get { return (string)GetValue (TitleProperty); } set { SetValue (TitleProperty, value); } }

Then I want to use it in a label in the XAML as such:

<Label Text="{TemplateBinding Title}" />

However, the TemplateBinding MarkupExtension doesn't exist so I get a XamlParseException.

I can already think of a workaround which is naming the label with an x:Name="MyLabel" and changing the Text value in the propertyChanged delegate with the newValue, but is there a better way to do that?

I do NOT require custom renderers for this control and want to do it all in XAML if possible. Thanks in advance!

Update: Pete answered it. Just use {Binding } and set the BindingContext Properly.

Here's how I got it to work.

            var pageContent = new CustomControl ();
        pageContent.SetBinding (CustomControl.TitleProperty, new Binding(path: "Title"));
        pageContent.BindingContext = new {Title = "This is the title that's databound!"};

Doesn't look like the default value in the BindableProperty works though..

1

1 Answers

1
votes

I'm not sure if this helps perhaps?

<Label Text="{Binding Title}"/>

remembering to set the BindingContext also?