从示例代码中,Label 位于 DataTemplate 内部。我们不能 get 或 set Text by x:Name = "txtInhoud" ,因为它已经与 ItemsSource 绑定。
<swipeCardView:SwipeCardView
ItemsSource="{Binding CardItems}"
SwipedCommand="{Binding SwipedCommand}"
LoopCards="{Binding IsLoopCards}"
VerticalOptions="FillAndExpand">
<swipeCardView:SwipeCardView.ItemTemplate>
<DataTemplate>
<Label x:Name="txtInhoud" Text="{Binding .}" FontSize="Large" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" BackgroundColor="Beige" />
</DataTemplate>
</swipeCardView:SwipeCardView.ItemTemplate>
</swipeCardView:SwipeCardView>
可以看到swipeCardView:SwipeCardView绑定了ItemsSource="{Binding CardItems}",这个ContentPage绑定了BindingContext = new SimplePageViewModel();。
那么Label的文字就是从SimplePageViewModel设计的。
public class SimplePageViewModel : BasePageViewModel
{
private ObservableCollection<string> _cardItems;
private bool _isLoopCards;
private string _message;
public SimplePageViewModel()
{
_cardItems = new ObservableCollection<string>();
for (var i = 1; i <= 5; i++)
{
_cardItems.Add($"Card {i}");
}
_isLoopCards = true;
SwipedCommand = new Command<SwipedCardEventArgs>(OnSwipedCommand);
ClearItemsCommand = new Command(OnClearItemsCommand);
AddItemsCommand = new Command(OnAddItemsCommand);
}
public ObservableCollection<string> CardItems
{
get => _cardItems;
set
{
_cardItems = value;
RaisePropertyChanged();
}
}
...
}
从上面的代码中,你会看到CardItems添加了五个string元素。由于Label与Text="{Binding .}"绑定文本,那么每个Label的Text就是CardItems的每个string元素。
此外,我们可以为 ViewModel 中的每个 Item 添加自定义的 Name 属性。例如修改CardItems如下:
...
private ObservableCollection<CardItem> _cardItems;
private bool _isLoopCards;
private string _message;
public SimplePageViewModel()
{
_cardItems = new ObservableCollection<CardItem>();
for (var i = 1; i <= 5; i++)
{
_cardItems.Add(new CardItem() { Name = $"Custom Card {i}" });
}
_cardItems[0].Name = "This is the first Card Item";
_isLoopCards = true;
SwipedCommand = new Command<SwipedCardEventArgs>(OnSwipedCommand);
ClearItemsCommand = new Command(OnClearItemsCommand);
AddItemsCommand = new Command(OnAddItemsCommand);
}
...
CardItem 定义如下:
public class CardItem
{
public string Name { set; get; }
}
Xaml还需要修改Text绑定键为:<Label Text="{Binding Name}" ...
现在效果: