我想使用CommunityToolkit在具有state = false的CollectionView中显示数据。Mvvm,但我不太明白该怎么做。我想使用ICollectionView,但没有在maui中找到它。请帮帮我
public class Task
{
public string Title { get; set; }
public string Text { get; set; }
public bool State { get; set; }
public DateTime CreateDate { get; set; }
}
ViewModel
public partial class ToDoViewModel : ObservableObject
{
[ObservableProperty]
string title;
[ObservableProperty]
string text;
[ObservableProperty]
bool state = false;
[ObservableProperty]
DateTime createDate = DateTime.Now.Date;
[ObservableProperty]
ObservableCollection<Task> tasks;
int count = 1;
public ToDoViewModel()
{
tasks = new ObservableCollection<Task>();
}
[RelayCommand]
void Add()
{
if (string.IsNullOrEmpty(text))
return;
Task task = new Task
{
Title = $"Task #{count}",
Text = text,
State = state,
CreateDate = createDate
};
tasks.Add(task);
count++;
}
[RelayCommand]
void Remove(Task task)
{
if (tasks.Contains(task))
tasks.Remove(task);
}
[RelayCommand]
void StateDone(Task task)
{
task.State = true;
}
}
首先,您需要设置一个CollectionView
:
public ICollectionView TasksView { get; set; }
当你初始化你的ViewModel时,你可以使用CollectionView的源代码,最终添加一些排序。然后你需要更新CollectionView过滤器:
public ToDoViewModel()
{
tasks = new ObservableCollection<Task>();
TasksView = new CollectionViewSource { Source = tasks }.View;
TasksView.SortDescriptions.Add(new SortDescription("Title", ListSortDirection.Ascending));
this.updateTasksView();
}
private void updateTasksView()
{
if (ListStockBeamView != null)
{
TasksView.Filter = new Predicate<object>(getFilteredTasksView);
}
}
private bool getFilteredTasksView(object obj)
{
Task task = (Task)obj;
if (task.State==true) return false;//you could just write return !task.State
if(task.Title=="") return false // i.e you want to hide tasks without title
return true;
}
我总是在一个函数中设置过滤器,因为在将来,如果你想添加一个复选框,选择state==true
或state==false
,甚至过滤文本标题,或任何其他过滤器,很容易添加附加过滤器,然后每次编辑过滤器时启动该功能
我为您编写了一个简单的演示,CollectionView
可以在MAUI中使用。
我注意到你写了一个模型文件和一个ViewModel文件。所以我写了xaml文件
<CollectionView ItemsSource="{Binding tasks}" >
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding Title }" IsVisible="{Binding State}"></Label>
<Label Text="{Binding Text }"></Label>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
在xaml中,我将状态绑定到IsVisible
,这样您就可以过滤您想要看到的数据。
另一种使用state
的方法是通过使用LINQ
来选择状态为true的数据
var TasksQuery =
from task in tasks
where task.State == "true"
select task;
然后你可以使用状态为true的TaskQuery。