[英]How to refresh XAML view in MAUI?
我正在制作一个应用程序,我可以根据列表动态生成布局。
<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>
该列表是这样绑定的:
taskList.ItemsSource = company.tasks;
每当我向列表中添加新项目时,我都想刷新它。
我尝试将列表重新绑定到ItemsSource
,但它不起作用:
taskList.ItemsSource = company.tasks;
我应该怎么做? 我可以只刷新视图以便它再次生成所有内容吗?
您应该使用一个IEnumerable
集合来为 ItemsSource 发送属性更改通知(例如ObservableCollection ),然后简单地添加到基础集合中。 这是一个例子:
ObservableCollection<string> tasks = new();
taskList.ItemsSource = tasks;
tasks.Add("Do something");
您不应从代码隐藏中分配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 将是这样的:(注意绑定而不是名称)
<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:我不会将数据 object 称为“任务”,或者给它一个更好的描述。 任务信息/公司任务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.