将按钮文本绑定到Carouselview中的变量

时间:2018-07-05 00:49:23

标签: c# xamarin xamarin.forms carousel

我对Xamarin还是陌生的,我正在尝试将文本数据绑定到我想在轮播视图中存在的按钮。我无法显示或显示文本按钮。当按钮在轮播视图之外时,绑定起作用,因为我可以使用x:Name。我的研究告诉我,我无法在轮播中使用x:Name,因为它期望控件会发生变化。

该按钮显示日期,当您向左或向右滑动时,日期将相应更改,我可以通过滑动来更改日期,但什么也看不到。

            <forms:CarouselView x:Name="MainCarouselView" Grid.Row="1" >
                <forms:CarouselView.ItemTemplate>
                    <DataTemplate>
                        <Button Text="{Binding buttonDate}" BackgroundColor="Red"/>
                    </DataTemplate>
                </forms:CarouselView.ItemTemplate>
            </forms:CarouselView>

后面的代码如下。

public MyPage()
{           
   InitializeComponent();

   this.BindingContext = this;
   var buttonDate = new DateButton
   {
       ButtonDate = DateTime.Now.ToString()
   };
}

public class DateButton
{
    public string ButtonDate { get; set; }
}

感谢任何指针。

1 个答案:

答案 0 :(得分:2)

public class Item {
  DateTime Date { get; set; }
}

var data = new List<Item>();

data.Add(new Item { Date = DateTime.Now };
data.Add(new Item { Date = DateTime.Now.AddDays(1) };
data.Add(new Item { Date = DateTime.Now.AddDays(2) };

MainCarouselView.ItemsSource = data;

因为您的ItemsSource是List<Item>,所以数据模板的绑定上下文将是Item当前处于“活动”状态的任何内容,因此Binding Path应该是Property Item

<Button Text="{Binding Date}" BackgroundColor="Red"/>
相关问题