Xamarin TemplatedBinding not working with attached Property

120 Views Asked by At

So I have a simple TableView in Xamarin where each row connects to a ControlTemplate. I wanted to set some attributes using attached properties on the ControlTemplate from the ViewCells however, no matter what I try the TemplateBindings seem to ignore the attached Properties.

So here is the ControlTemplate:

<ControlTemplate x:Key="ResultTemplate">
            <StackLayout Margin="20,0,20,0"
                         BackgroundColor="{TemplateBinding attachableProperties:ColorProperties.BackgroundColor}">
                <StackLayout Margin="0,5,0,0">
                    <ContentPresenter />
                    <controls:Separator />
                </StackLayout>
            </StackLayout>
</ControlTemplate>

I Connect to this Template with the following piece of code from inside a ViewCell:

<ViewCell>
          <ContentView ControlTemplate="{StaticResource ResultTemplate}"
                       attachableProperties:ColorProperties.BackgroundColor="{StaticResource OddRowBackgroundColor}">
                <Label Text="Hi" />
          </ContentView>
</ViewCell>

Finally here is the code for the attached property:

public static readonly BindableProperty BackgroundColorProperty = BindableProperty.CreateAttached(
        "BackgroundColor",
        typeof(Color),
        typeof(ColorProperties),
        Color.Red,
        propertyChanged: ((bindable, value, newValue) =>
        {
            System.Diagnostics.Debug.WriteLine(value);
        }));

    public static Color GetBackgroundColor(BindableObject obj)
    {
        return (Color) obj.GetValue(BackgroundColorProperty);
    }

    public static void SetBackgroundColor(BindableObject obj, Color value)
    {
        obj.SetValue(BackgroundColorProperty, value);
    }

I've added the Debug.Writeline to the propertyChanged parameter to see if it gets called, and so it does. So the problem in my opinion does have to lie with the TemplateBinding. But why does it not work, I can not get my head around why the TemplateBinding does not connect to the attached property.

1

There are 1 best solutions below

0
Ax1le On

You have to place your logic code in propertyChanged:

public static readonly BindableProperty BackgroundColorProperty = BindableProperty.CreateAttached(
"BackgroundColor",
typeof(Color),
typeof(ColorProperties),
Color.Red,
propertyChanged: ((bindable, value, newValue) =>
{
    System.Diagnostics.Debug.WriteLine(value);

    var control = bindable as View;
    if (control != null)
    {
        control.BackgroundColor = (Color)newValue;
    }
}));