ObservableCollection不更新控件

时间:2012-03-04 20:02:13

标签: c# wpf xaml

我正在使用Telerik TransitionControl向最终用户显示广告。逻辑的编写方式是广告图像将在后面异步下载。控件将显示可用的图像。我使用ObservableCollection来保存广告图像。成功下载图像时,新的图像信息被添加到此ObservableCollection中。但是,Telerik TransitionControl没有使用新图像进行更新。

我相信ObservableCollection不需要调用OnNotifyPropertyChanged,因为它将在内部调用

代码如下:

//Inside the AdvertUserControl.xaml.cs

ViewModel vm = new ViewModel();
DataContext = vm;

this.radControl.SetValue(AdRotatorExtensions.AdRotatorExtensions.ItemsSourceProperty, vm.SquareAdsVertical);

//在ViewModel.cs内部

 public ReadOnlyObservableCollection<Advert> SquareAdsVertical
        {
            get
            {
                if (AdsManager.VerticalAds == null)
                {

                    return null;
                }
                return new ReadOnlyObservableCollection<Advert>(AdsManager.VerticalAds);
            }
        }


// Inside DownloadManager.cs
   private static ObservableCollection<Advert> adsToShowVertical = new ObservableCollection<Advert>();
public static ObservableCollection<Advert> VerticalAds
        {
            get { if (adsToShowVertical != null) return adsToShowVertical;
                return null;
            }
        }

 public static void OnDownloadComplete(Object sender, AsyncCompletedEventArgs e)
{
        try
        {


    if(!e.Cancelled)
    {

        if (e.Error == null)
        {
            Advert ad = e.UserState as Advert ;
         adsToShowVertical.Add(ad  );
        }

}

2 个答案:

答案 0 :(得分:1)

我没有使用Telerik控件,但我怀疑如果您在View模型中更改以下代码

public ReadOnlyObservableCollection<Advert> SquareAdsVertical 
{ 
    get 
    { 
        if (AdsManager.VerticalAds == null) 
        { 
            return null; 
        } 
        return new ReadOnlyObservableCollection<Advert>(AdsManager.VerticalAds); 
    } 
} 

以下

private ReadOnlyObservableCollection<Advert> _readonlyAds;
public ReadOnlyObservableCollection<Advert> SquareAdsVertical 
{ 
    get 
    { 
        if (AdsManager.VerticalAds == null) 
        { 
            return null; 
        } 
        else if (_readonlyAds == null)
        {
            // Only one instance of the readonly collection is created
            _readonlyAds = new ReadOnlyObservableCollection<Advert>(AdsManager.VerticalAds);
        }

        // Return the read only collection that wraps the underlying ObservableCollection
        return  _readonlyAds;
    } 
} 

答案 1 :(得分:0)

您只需要返回从可观察集合创建的只读集合的​​一个实例。如果您更改Observable列表中的值,您的控件将通过readonly集合进行刷新。