Привязка команд ControlTemlate - PullRequest
1 голос
/ 13 марта 2020

Microsoft документация показывает, как наследовать от ControlTemplate и использовать ContentPresenter.

Показывает, как использовать строковые свойства для заполнения связанных строк строк в шаблоне. (например, HeaderText)

Это не показывает, как сделать то же самое с командами. Я хочу управлять командным поведением кнопки в шаблоне с помощью реализации contentpage / viewmodel.

Следуя примеру со свойством, я попробовал то же самое с ICommand, но он игнорируется. Это означает, что кнопка не выполняет предоставленную команду. Командование не поддерживается?

Пример Это в моем ControlTemplate, называемом Application Chrome .xaml

                <Label Grid.Row="0"
                   Margin="20,0,0,0"
                   Text="{TemplateBinding HeaderText}"
                   TextColor="White"
                   FontSize="Title"
                   VerticalOptions="Center"/>

                  <Button Grid.Column="0"
                        x:Name="LeftButton"
                        Margin="20,0,0,0"
                        Text="Change Label"
                        TextColor="White"
                        HorizontalOptions="Start"
                        VerticalOptions="Center"
                        Command="{TemplateBinding LeftButtonTemplateCommand}"

Кодовый код определяет оба свойства Bindable

    public static readonly BindableProperty HeaderTextProperty = BindableProperty.Create("HeaderText", typeof(string), typeof(ContentPage), null, BindingMode.TwoWay);
    public string HeaderText
    {
        get => (string)GetValue(HeaderTextProperty);
        set => SetValue(HeaderTextProperty, value);
    }


    public static readonly BindableProperty LeftButtonTemplateCommandProperty = BindableProperty.Create("LeftButtonCommand", typeof(ICommand), typeof(ApplicationChrome), null);

    public ICommand LeftButtonTemplateCommand
    {
        get => (ICommand) GetValue(LeftButtonTemplateCommandProperty);
        set => SetValue(LeftButtonTemplateCommandProperty, value);
    }

Мое реализующее представление устанавливает оба Bindables

<core:ApplicationChrome xmlns="http://xamarin.com/schemas/2014/forms" 
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:core="clr-namespace:FEOD.Core;assembly=FEOD"
         mc:Ignorable="d"
         HeaderText="FE | Home"
         LeftButtonTemplateCommand="{Binding LeftButtonCommand}"
         x:Class="FEOD.Views.HomeView">

BindingContext реализующего представления установлен в его viewmodel, который определяет LeftButtonCommand

    public ICommand LeftButtonCommand { get; private set; }

    private static void OnLeftButtonClicked(object obj)
    {
        var a = 1;
    }

    public HomeViewModel()
    {
        LeftButtonCommand = new Command(OnLeftButtonClicked);
    }

Связанный HeaderText очень хорошо отображает «FE | Home». Но связанная команда никогда не запускает OnLeftButtonClicked.

1 Ответ

1 голос
/ 13 марта 2020

Первый параметр метода BindableProperty.Create () должен быть "LeftButtonTemplateCommand", а не "LeftButtonCommand". Имя свойства должно точно соответствовать Binding для работы.

...