Как заставить локальный ContentView связывать текст метки - PullRequest
0 голосов
/ 05 мая 2020

Я сделал ContentView с помощью Expander. Я хочу дублировать этот код Xaml несколько раз в другом файле Xaml. Но я хочу, чтобы для каждого расширителя была своя привязка.
Я связал этот код (код 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:expandable="clr-namespace:Expandable;assembly=ExpandableView"
             x:Class="Hello.ExpandableView">
    <ContentView.Content>
        <expandable:ExpandableView Padding="5">
    <expandable:ExpandableView.PrimaryView>
        <Frame BackgroundColor="White" Padding="5" CornerRadius="10">
            <StackLayout Orientation="Horizontal">
        <Label x:Name="label" FontSize="16" TextColor="Black" FontAttributes="Bold" Padding="5" HorizontalTextAlignment="Start" HorizontalOptions="StartAndExpand"/>
        <Image Source="arrow.png" WidthRequest="25" HeightRequest="25" Margin="5"/>
                </StackLayout>
    </Frame>
    </expandable:ExpandableView.PrimaryView>
    <expandable:ExpandableView.SecondaryViewTemplate>
        <DataTemplate>
            <Frame BackgroundColor="White" Padding="5" CornerRadius="10">
        <Label Text="{Binding Tip1Uitleg}" FontSize="15" TextColor="Black" Padding="5"/>
                </Frame>
        </DataTemplate>
    </expandable:ExpandableView.SecondaryViewTemplate>
</expandable:ExpandableView>
    </ContentView.Content>
</ContentView>
namespace Hello
{
    public partial class ExpandableView : ContentView
    {
        public static BindableProperty LabelProperty =
    BindableProperty.Create(nameof(Label),
                            typeof(string),
                            typeof(ExpandableView),
                            propertyChanged: (b, o, n) => (b as ExpandableView).OnLabelChanged());

        private void OnLabelChanged()
        {
            label.Text = Label; //label is the x:Name of your Label control in ExpandableView.xaml
        }

        public string Label
        {
            get => (string)GetValue(LabelProperty);
            set => SetValue(LabelProperty, value);
        }
    }
}

С этим кодом: Это работает:

<local:ExpandableView Label="Hello"/>

Но я хочу этого. Это не работает:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:expandable="clr-namespace:Expandable;assembly=ExpandableView"
             xmlns:local="clr-namespace:Hello"
             x:Class="Hello.Health.HealthDetail"
             Title="{Binding Name}">
     <ContentPage.Content>
     <ScrollView>
        <StackLayout>
            <Image Source="{Binding Image}"/>
            <Label Text="{Binding Tip1Uitleg}" FontSize="15" TextColor="Black" Padding="10, 5, 10, 5"/>

            <local:ExpandableView Label="{Binding Tip1}"/> //This is what it is all about
</StackLayout>
            </ScrollView>
    </ContentPage.Content>
</ContentPage>

CodeBehind:

namespace Hello.Health
{
    public partial class HealthDetail : ContentPage
    {
        public HealthDetail(HealthStrings healthStrings)
        {
            if (healthStrings == null)
                throw new ArgumentNullException();

            BindingContext = healthStrings;

            InitializeComponent();


        }
    }
}

Как мне заставить это работать? Я должен сделать это выше более динамичным c, но я не знаю, как.

Кстати, это тоже работает:

<Label Text="{Binding Tip1}" />

Прошу прощения за неясное объяснение, я надеюсь, что кто-то может мне помочь. Спасибо за уделенное время :)

Ответы [ 2 ]

0 голосов
/ 06 мая 2020

Обычно, когда вы хотите привязать значение для binableproperty, вы можете попробовать следующий код:

ExpandableView : я делаю для вас простой просмотр содержимого с тем же binableproperty.

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
x:Class="XamarinDemo.Pages.ExpandableView">
   <ContentView.Content>
       <StackLayout>
          <Label Text="Hello"></Label>
          <Label x:Name="label"></Label>
       </StackLayout>
   </ContentView.Content>
</ContentView>

Код позади:

public partial class ExpandableView : ContentView
 {
    public static BindableProperty LabelProperty =
 BindableProperty.Create(nameof(Label),
                        typeof(string),
                        typeof(ExpandableView),
                        propertyChanged: (b, o, n) => (b as 
ExpandableView).OnLabelChanged());

    private void OnLabelChanged()
    {
        label.Text = Label; //label is the x:Name of your Label control in ExpandableView.xaml
    }

    public string Label
    {
        get => (string)GetValue(LabelProperty);
        set => SetValue(LabelProperty, value);
    }
    public ExpandableView()
    {
        InitializeComponent();
    }

 }

Использование:

 <ContentPage.Content>
    <local:ExpandableView Label="{Binding str}"></local:ExpandableView>
</ContentPage.Content>

Код позади:

public partial class Page1 : ContentPage
  {
    public string str { get; set; }
    public Page1()
    {
        InitializeComponent();

        str = "okay";

        this.BindingContext = this;
     }
 }

enter image description here

0 голосов
/ 05 мая 2020

Вы не должны привязываться к this, так как вы используете BindableProperty. Вместо этого вам следует обновить свойство Label.Text при изменении значения BindableProperty.

public static BindableProperty LabelProperty =
    BindableProperty.Create(nameof(Label),
                            typeof(string),
                            typeof(ExpandableView),
                            propertyChanged:(b, o, n) => (b as ExpandableView).OnLabelChanged());

private void OnLabelChanged()
{
    label.Text = Label; //label is the x:Name of your Label control in ExpandableView.xaml
}

public string Label
{
    get => (string)GetValue(LabelProperty);
    set => SetValue(LabelProperty, value);
}
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="YourProject.ExpandableView">
    <Grid>
        <Label x:Name="label"/>
    </Grid>
</ContentView>
...