我正在制作一个应用程序,其中布局根据列表动态生成。
<StackLayout>
<CollectionView x:Name="taskList">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="models:Task">
<VerticalStackLayout Margin="15">
<Entry Text="{Binding name}" IsReadOnly="True" />
<Entry Text="{Binding departmentsString}" IsReadOnly="True"/>
<HorizontalStackLayout>
<Entry Text="{Binding status}" IsReadOnly="True"/>
<Entry Text="{Binding deadline}" IsReadOnly="True" />
<Entry Text="{Binding author.fullName}" IsReadOnly="True"/>
</HorizontalStackLayout>
<Entry Text="{Binding description}" IsReadOnly="True" />
</VerticalStackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
列表的绑定(bind)方式如下:
taskList.ItemsSource = company.tasks;
每当我向列表中添加新项目时,我都想刷新它。
我尝试将列表重新绑定(bind)到 ItemsSource
但它不起作用:
taskList.ItemsSource = company.tasks;
我该怎么做?我可以刷新 View 以便它再次生成所有内容吗?
最佳答案
您应该绑定(bind)一个自定义集合,而不是从代码隐藏中分配 ItemsSource
,这样可以更轻松地实现 UI 和逻辑的解耦。阅读更多 MVVM模式。
(我这里没有IDE,所以没有测试)
你可以这样做:
// data class
public class TaskInfo
{
public string name {get; set;}
public string departmentsString {get;set;}
}
// you page/view whatever code behind the xaml
public class YourPage : // insert the class which it is derived from.
{
// create a collection property, which generates events when changed. The UI react on these events.
public ObservableCollection<TaskInfo> Tasks {get;} = new();
public YourPage()
{
InitComponentsOrSomething();
// assign the datacontext (which the view binds to)
this.DataContext = this;
}
}
你的 xaml 会是这样的:(注意绑定(bind)而不是名称)
<StackLayout>
<CollectionView ItemsSource="{Binding Tasks}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="models:Task">
<VerticalStackLayout Margin="15">
<Entry Text="{Binding name}" IsReadOnly="True" />
<Entry Text="{Binding departmentsString}" IsReadOnly="True"/>
<HorizontalStackLayout>
<Entry Text="{Binding status}" IsReadOnly="True"/>
<Entry Text="{Binding deadline}" IsReadOnly="True" />
<Entry Text="{Binding author.fullName}" IsReadOnly="True"/>
</HorizontalStackLayout>
<Entry Text="{Binding description}" IsReadOnly="True" />
</VerticalStackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
如果要将项目添加到集合中,只需使用 Tasks
属性即可:
Tasks.Add(new TaskInfo { name = "some name", departmentsString = "Enter here" });
ps:我不会将数据对象称为“任务”,或者给它一个更好的描述。任务信息/公司任务。
关于c# - 如何在 MAUI 中刷新 XAML View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74935025/