概述
我有一个应用程序,它显示来自可观察集合的数据。可观察集合(在此调试设置中)仅创建和实例化一次,然后值保持不变。
应用程序的主视图包含一个绑定到所述可观察集合的 ListBox:
<ListBox x:Name="MainListBox" ItemsSource="{Binding Items}" SelectionChanged="MainListBox_SelectionChanged" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel MinWidth="456" MaxWidth="456" Background="White" Margin="0,0,0,17">
<sparklrControls:SparklrText Post="{Binding Path=.}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<!-- Workaround used to stretch the child elements to the full width -> HorizontalContentAlignment won't work for some reason... -->
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
子项绑定到 UserControl。此 UserControl 实现了子元素绑定到的 DependancyProperty:
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(object), new PropertyMetadata(textPropertyChanged));
private static void postPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SparklrText control = d as SparklrText;
control.Post = (ItemViewModel)e.NewValue;
}
绑定到 post 属性通过Post属性的 getter 配置其他变量
public ItemViewModel Post
{
get
{
return post;
}
set
{
if (post != value)
{
this.ImageLocation = value.ImageUrl;
this.Username = value.From;
this.Comments = value.CommentCount;
this.Likes = value.LikesCount;
this.Text = value.Message;
post = value;
}
}
}
此设置器配置其他设置器,这些设置器依次设置用户控件中的元素。用户控件中没有任何内容是绑定的,少数更新是通过直接访问相应的内容/文本属性来完成的。ImageLocation 执行图像的异步下载
private void loadImage(string value)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += (sender, e) =>
{
image = new BitmapImage();
image.SetSource(e.Result);
MessageImage.Source = image;
};
wc.OpenReadAsync(new Uri(value));
}
问题
当我在列表框中向下滚动并备份时,当拥有的元素重新出现时,将执行Post的设置器。问题:值是 ItemViewModel 的不同实例。ListBox ItemsSource 不能以任何方式从类外部访问。向上滚动时,似乎错误的项目绑定到元素,导致设计失真。绑定是否存在导致此问题的任何问题?