Xamarin TemplatedBinding не работает с прикрепленным свойством - PullRequest
0 голосов
/ 06 июня 2019

Итак, у меня есть простой TableView в Xamarin, где каждая строка соединяется с ControlTemplate. Я хотел установить некоторые атрибуты, используя вложенные свойства на ControlTemplate из ViewCells, однако, независимо от того, что я пытаюсь, TemplateBindings, похоже, игнорирует присоединенные свойства.

Итак, вот 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>

Я подключаюсь к этому шаблону со следующим фрагментом кода внутри ViewCell:

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

Наконец, вот код для прикрепленного свойства:

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);
    }

Я добавил Debug.Writeline к параметру propertyChanged, чтобы посмотреть, вызывается ли он, и так оно и есть. Так что проблема, на мой взгляд, должна лежать в TemplateBinding. Но почему это не работает, я не могу понять, почему TemplateBinding не подключается к присоединенному свойству.

1 Ответ

0 голосов
/ 07 июня 2019

Вы должны поместить свой логический код в 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;
    }
}));
...