我有以下标签:
<Label Text="{x:Static local:FontAwesome.FACheck}" FontFamily="FontAwesome" TextColor="Green"/>
按钮上的事件:
correctButton.Clicked += (sender, e) =>
{
App.DB.IncrementScore();
};
这样做的目的是,每次我单击一个按钮时,我的分数都会增加 1。我想做的也是根据分数增加 Label
的数量。请参阅下面的附图:
有人知道我怎样才能做到这一点吗?
最佳答案
这个问题有不同的解决方案。在选择一个之前一定要通读所有这些 - 我最喜欢的(最简单的一个)一直列在下面......
方法 #1:
正如一些人所建议的,您可以创建一些集合控件(我稍后会谈到),在 ViewModel 中定义一个 ObservableCollection
,设置页面的 Binding Context
到该 ViewModel 的实例,并在单击按钮时将项目添加到集合中:
public class MyViewModel()
{
public ObservableCollection<int> Items { get; set; } = new ObservableCollection<int>();
}
private MyViewModel _viewModel = new MyViewModel();
public MainPage()
{
InitializeComponent();
BindingContext = _viewModel;
}
correctButton.Clicked += (sender, e) =>
{
App.DB.IncrementScore();
_viewModel.Items.Add(0);
};
ObservableCollection
的类型实际上并不重要,因为我们对所有项目使用相同的静态 ItemTemplate
:
<ContentPage.Resources>
<DataTemplate x:Key="ScoreItemTemplate">
<ViewCell>
<ViewCell.View>
<Label Text="{x:Static local:FontAwesome.FACheck}" FontFamily="FontAwesome" TextColor="Green"/>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ContentPage.Resources>
此方法的主要问题是 Xamarin.Forms ListView
无法水平显示其项目。这意味着,您需要下载可用的 HorizontalListView
Nuget 包之一,或使用 built-in (only in Xamarin.Forms 2.3 and above!) CarouselView
:
<CarouselView ItemTemplate="{StaticResource ScoreItemTemplate}" ItemsSource="{Binding Items}"/>
然后,如果您选择使用水平 ListView,您可能希望花一些时间移除所有用于在轮播中滑动和选择项目的视觉效果...
相反,有两种更省力的替代解决方案:
方法 #2:
显然,简单的方法是在代码中创建"template"标签:
private Label CreateScoreLabel()
{
return new Label {Text = FontAwesome.FACheck, TextColor = Color.Green, FontFamily = "FontAwesome"};
}
...向页面添加一个水平的StackLayout
:
<StackLayout Orientation="Horizontal" x:Name="LabelStack"/>
...并以困难的方式添加新标签:
correctButton.Clicked += (sender, e) =>
{
App.DB.IncrementScore();
LabelStack.Children.Add(CreateScoreLabel());
};
但是,对于仅创建一个绿色复选标记列表而言,所有这一切似乎都相当老套。这导致我们...
...方法 #3:
从技术上讲,这并不完全符合您的要求(增加标签的数量),但根据您的屏幕截图,它可能会以更简单的方式满足您的需求。
删除现有标签的文本(因为它在启动时不显示任何内容),而是给它一个唯一的名称:
<Label x:Name="ScoreLabel" FontFamily="FontAwesome" TextColor="Green"/>
现在,为 string
类型定义一个简单的扩展方法,将给定的字符串重复一定次数:
public static class StringExtensions
{
public static string Repeat(this string input, int num)
{
return String.Concat(Enumerable.Repeat(input, num));
}
}
(有多种方法可以使这个repeat 函数尽可能高效,我只是选择了最简单的一行代码,搜索 StackOverflow 进行详细讨论...)
您现在可以使用 XAML 中定义的单个 Label
控件,只需在单击按钮时为其分配几个复选标记:
correctButton.Clicked += (sender, e) =>
{
App.DB.IncrementScore();
ScoreLabel.Text = FontAwesome.FACheck.Repeat(App.DB.Score); // replace parameter by whatever method allows you to access the current score number
};
当然,这种方法也可以适应 MMVM 方式,通过简单地使用公共(public)可绑定(bind) string
属性而不是直接设置标签的 Text
属性,但是为此,我建议您查看初学者的 MVVM 教程。
关于c# - 在 Xamarin Forms 中添加多个标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41647795/