friend 们大家好,我在 Windows 应用商店应用程序的 async 方法中使用 ObservableCollection 时遇到了非常奇怪的问题。我正在尝试以异步方法在 ObservableCollection 中添加项目,如果我在 wait 关键字所在的行上方定义 ObservableCollection ,那么它工作正常,但我在该行下方初始化它不起作用。我已经为这个问题制作了样本。 我的 xaml 代码是..
<Page
x:Class="observableCollectionTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:observableCollectionTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<ListView ItemsSource="{Binding SomeCollection}" Background="Pink" HorizontalAlignment="Left" Width="500" >
<ListView.ItemTemplate>
<DataTemplate>
<Grid Width="200" Height="200" Background="Red" >
<Button Content="click me" Name="btn" ></Button>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
我的主页反手工作代码是..
public sealed partial class MainPage : Page
{
public ObservableCollection<string> SomeCollection { get; set; }
public MainPage()
{
this.InitializeComponent();
FillCollection();
this.DataContext = this;
}
public async Task FillCollection()
{
SomeCollection = new ObservableCollection<string>(); // it is working..
HttpClient client = new HttpClient();
HttpResponseMessage message = await client.GetAsync("https://www.google.co.in/");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
}
我的主页反手 FillCollection 代码不起作用..
public async Task FillCollection()
{
HttpClient client = new HttpClient();
HttpResponseMessage message = await client.GetAsync("https://www.google.co.in/");
SomeCollection = new ObservableCollection<string>(); // this is not working
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
}
我不明白为什么会发生这种情况。我在这里缺少一些概念,请告诉我..任何类型的帮助或建议表示赞赏..
最佳答案
您缺少从 SomeCollection
属性触发的属性更改事件 - 请参阅 this关于如何实现这一点。
需要它的原因是,异步之前的 FillCollection
方法的一部分在分配 DataContext
属性之前执行,而另一半则在 Web 请求完成后执行。因此,在您不起作用的示例中,View
不知道整个集合已更改。
另一方面,请考虑在每次列表刷新时分配 ObservableCollection
的新实例会失去什么(您想在某个时刻刷新它吗?)。该类的底层是提供 UI 方式来优化 ItemsControl
中项目的刷新,方法是在创建整个 ListView
的新集合时了解添加/删除/移动哪些元素将被重新渲染,这可能会很昂贵。出于代码清晰的原因,我建议在调用 FillCollection
之前将您的赋值移至构造函数,并很好地处理内容更改 - 这对您来说是更多工作,但如果 View 很复杂,那么这是值得的。
关于c# - 异步方法中的可观察集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19086968/