Повторно используемый ContentView в формах Xamarin - PullRequest
0 голосов
/ 30 октября 2018

Я создал контент-представление отдельно, так что я могу повторно использовать его в разных ContentPage.

Вот мой ContentView.XAML

<?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:custom="clr-namespace:MyMXLibrary.Helpers"
         x:Class="MyMXLibrary.Views.AlertView" 
         x:Name="this">
<ContentView.Content>
    <Frame VerticalOptions="Center" HorizontalOptions="Center">
        <StackLayout>
            <Label Text="{Binding Source={x:Reference this}, Path=Heading}"/>
            <Label Text="{Binding Source={x:Reference this}, Path=Message}"/><Label Text="Cancel">
                <Label.GestureRecognizers>
                    <TapGestureRecognizer Command="{Binding CancelCommand}" />
                </Label.GestureRecognizers>
            </Label>
            <Label Text="Ok">
                <Label.GestureRecognizers>
                    <TapGestureRecognizer Command="{Binding ProceedCommand}" />
                </Label.GestureRecognizers>
            </Label>
        </StackLayout>
    </Frame>
</ContentView.Content></ContentView>

Вот мой ContentView.Xaml.cs

 public partial class AlertView : ContentView
{
    public static readonly BindableProperty HeadingTextProperty = BindableProperty.Create(nameof(Heading), typeof(string), typeof(Label));
     public static readonly BindableProperty MessageTextProperty = BindableProperty.Create(nameof(Message), typeof(string), typeof(Label));

    public string Heading { get { return (string)GetValue(HeadingTextProperty); } set { SetValue(HeadingTextProperty, value); } }
    public string Message { get { return (string)GetValue(MessageTextProperty); } set { SetValue(MessageTextProperty, value); } }

    public AlertView()
    {
        InitializeComponent();
    }      
}

Вот мой пример ContentPage.Xaml, где я планирую использовать созданное выше представление контента.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
          xmlns:alert="clr-namespace:MyMXLibrary.Views"
         x:Class="MyMXLibrary.Views.MyPage"
         Title="MyPage"><ContentPage.Content><ContentView >
      <alert:AlertView Heading="Test" Message="Sample" ></alert:AlertView></ContentView></ContentPage.Content></ContentPage>

работает нормально, если я использую статическое значение. Но вместо этого, если я связываю значение

<alert:AlertView Heading="Test" Message="{Binding sample}" ></alert:AlertView>

Я получаю сообщение об ошибке

No property, bindable property, or event found for 'Message', or mismatching type between value and property

Как я могу сделать привязку здесь. Поскольку мое значение неизвестно, я не могу присвоить статическое значение в XAML, мне нужно использовать только Binding. Что я должен сделать здесь, чтобы связать значение, пожалуйста, помогите мне.

1 Ответ

0 голосов
/ 30 октября 2018

Я думаю, что у вас неправильный код создания BindableProperty. У вас есть:

public static readonly BindableProperty HeadingTextProperty = 
    BindableProperty.Create(nameof(Heading), typeof(string), typeof(Label));
public static readonly BindableProperty MessageTextProperty = 
    BindableProperty.Create(nameof(Message), typeof(string), typeof(Label));

Таким образом, третий параметр - typeof(Label), но это должен быть тип класса, который будет иметь свойство, в данном случае AlertView. Также по соглашению (не обязательно, если требуется) именем привязываемого свойства будет имя свойства + «Свойство». У вас есть имя свойства + "TextProperty". Так что попробуйте:

public static readonly BindableProperty HeadingProperty = 
    BindableProperty.Create("Heading", typeof(string), typeof(AlertView));
public static readonly BindableProperty MessageProperty = 
    BindableProperty.Create("Message", typeof(string), typeof(AlertView));

См. это для получения дополнительной информации. Вы увидите, что третьим параметром метода BindableProperty.Create является declaringType, который должен быть типом, определяющим свойство привязки.

пример проекта: https://www.dropbox.com/s/j7kpehpt8htrf8k/TestAlertView.zip?dl=0

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...