我有三个领域的模型:TItle,Body,Status。
public class Names
{ [PrimaryKey]
public string Title { get; set; }
public string Body { get; set; }
public string Status{ get; set; }}当用户打开页面时,他可以看到带有字段的名称列表(Title,Body)。页面代码如下:
xaml.cs
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HomePage : ContentPage
{
public ObservableCollection<Models.Names> items { get; set; }
public HomePage()
{
items = new ObservableCollection<Models.Names>();
this.BindingContext = this;
InitializeComponent();
List.ItemSelected += (sender, e) => {
((ListView)sender).SelectedItem = null;
};
List.Refreshing += (sender, e) => {
LoadUsersData();
};
LoadUsersData();
}
public async void LoadUsersData()
{
List.IsRefreshing = true;
var Names= await App.Database.Names.GetItemsAsync();
items.Clear();
foreach (var item in Names)
items.Add(item);
List.IsRefreshing = false;
}
}xaml
<StackLayout>
<ListView x:Name="List"
HasUnevenRows="True"
ItemsSource="{Binding items}"
IsPullToRefreshEnabled="True">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell
Text="{Binding Title}"
Detail="{Binding Body}"
TextColor="Black"
DetailColor="Gray">
</TextCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>在页面的开头,我想添加字符串,它用Status = "New“显示所有项的数量。我怎么能做到呢?
发布于 2018-03-11 03:21:20
添加一个绑定到您的Label的Count属性的ObservableCollection (每次从集合中添加/删除项目时都会通知它):
<Label Text="{Binding items.Count, StringFormat='Status = {0}'}"/>更新
如果您需要自定义属性,比如具有"new“的Names对象的数量,可以使用多种方法创建可绑定的属性,但一种方法是将ObservableCollection子类并添加自定义属性:
public class MyObservableCollection : ObservableCollection<Names>
{
public MyObservableCollection()
{
CollectionChanged += (object sender, NotifyCollectionChangedEventArgs e) =>
{
OnPropertyChanged(new PropertyChangedEventArgs("NewCount"));
};
}
public int NewCount
{
get { return this.Count((Names arg) => arg.Status == "new"); }
}
}现在将使用ObservableCollection替换为MyObservableCollection。
public MyObservableCollection items { get; set; }在XAML中,现在可以在NewCount上绑定
<Label Text="{Binding items.Count, StringFormat='Status = {0}'}"/>
<Label Text="{Binding items.NewCount, StringFormat='Status = {0}'}"/>就使用BindableProperty而言,已经发布了其他这样的问题/答案,还有一篇很棒的博客文章:
https://stackoverflow.com/questions/49216174
复制相似问题