Xamarin Forms - Установить BindingContext элемента управления - PullRequest
0 голосов
/ 17 апреля 2020

У меня есть заявление на получение форм xamarin. Он имеет вкладку внутри нескольких вкладок. Страница с вкладками и те вкладки, каждая из которых имеет свою собственную модель представления в качестве обязательного контекста.

В app.xaml я определил шаблон управления. Я использую этот шаблон элемента управления на каждой вкладке, потому что я хочу, чтобы на каждой из этих вкладок была кнопка внизу страницы.

В данный момент: кнопка в шаблоне элемента управления связывается со свойством, определенным на каждой вкладке. , Но я хочу, чтобы кнопка связывалась в одном месте. Разве нельзя создать специальную модель представления для шаблона элемента управления и связать кнопку, определенную в шаблоне элемента управления, с этой моделью представления?

Текущий код:

        <ControlTemplate x:Key="ActivityStatusButton">
            <StackLayout>

                <ContentPresenter>

                </ContentPresenter>

                <StackLayout VerticalOptions="EndAndExpand" HorizontalOptions="Fill" Padding="15">

                    <Button Style="{StaticResource RedBackGroundWithWhiteTextButtonStyle}" Command="{TemplateBinding BindingContext.ClickOnStatusButton, Mode=TwoWay}" Text="{TemplateBinding BindingContext.ok, Mode=TwoWay}"></Button>
                </StackLayout>

            </StackLayout>
        </ControlTemplate>

Типичная вкладка:

<ContentPage ...>

<ContentPage.Content>
    <Label Text="hello"></Label>
</ContentPage.Content>

<!--The control template is placed here (the button) -->

1 Ответ

1 голос
/ 17 апреля 2020

Вы можете создать пользовательский элемент управления (подкласс ContentView), например

<?xml version="1.0" encoding="UTF-8"?>
<ContentView 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"
             mc:Ignorable="d"

             x:Name="template"

             x:Class="App24.MyControlTemplate">
  <ContentView.Content>


        <StackLayout VerticalOptions="EndAndExpand" HorizontalOptions="Fill" Padding="15">

            <Button Clicked="Button_Clicked" Command="{Binding Source={x:Reference template},Path=ButtonCommand}" Text="{Binding  Source={x:Reference template},Path=ButtonText}" CommandParameter="{Binding  Source={x:Reference template},Path=CommandParameter}" />
        </StackLayout>

    </ContentView.Content>
</ContentView>
using System;

using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace App24
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MyControlTemplate : ContentView
    {
        public event EventHandler ButtonClick;

        public static readonly BindableProperty ButtonTextProperty =
        BindableProperty.Create("ButtonText", typeof(string), typeof(MyControlTemplate), default(string));

        public string ButtonText
        {
            get => ((string)GetValue(ButtonTextProperty));
            set => SetValue(ButtonTextProperty, value);
        }

        public static readonly BindableProperty ButtonCommandProperty =
        BindableProperty.Create("ButtonCommand", typeof(ICommand), typeof(MyControlTemplate), null, BindingMode.Default, null);


        public ICommand ButtonCommand
        {
            get => (ICommand)GetValue(ButtonCommandProperty);
            set
            {
                SetValue(ButtonCommandProperty, value);

            }
        }

        public static readonly BindableProperty CommandParameterProperty =
            BindableProperty.Create("CommandParameter", typeof(object), typeof(MyControlTemplate), null);

        public object CommandParameter
        {
            get => (object)GetValue(CommandParameterProperty);
            set => SetValue(CommandParameterProperty, value);
        }

        public MyControlTemplate()
        {
            InitializeComponent();

        }



        private void Button_Clicked(object sender, EventArgs e)
        {
            ButtonClick?.Invoke(sender, e);
        }
    }
}

Теперь вы можете добавить его на любую страницу и связать команду Text , или CommandParameter в коде позади.

<StackLayout VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">

        <local:MyControlTemplate   ButtonText="{Binding ButtonText}" ButtonCommand="{Binding ClickCommand}" CommandParameter="test" />

</StackLayout>
...