【问题标题】:ObservableCollection not updating the controlObservableCollection 不更新控件
【发布时间】:2012-03-04 20:02:12
【问题描述】:

我有一个 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  );
        }

}

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

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

    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;
        } 
    } 
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2013-12-05
        • 2016-05-19
        • 2014-08-31
        • 1970-01-01
        • 1970-01-01
        • 2017-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多