简体   繁体   English

属性的索引器可以在Windows Phone 8的xaml绑定中工作吗?

[英]Can Indexers of a property work in xaml binding in windows phone 8?

something i do wrong? 我做错了什么? anyone gives some suggestions 任何人都给一些建议

according to msdn 根据msdn

Indexers of a property can be specified within square brackets following the property name where the indexer is applied. 可以在应用索引器的属性名称后面的方括号内指定属性的索引器。 For instance, the clause Path=ShoppingCart[0] sets the binding to the index that corresponds to how your property's internal indexing handles the literal string "0". 例如,子句Path = ShoppingCart [0]将绑定设置为与属性的内部索引如何处理文字字符串“ 0”相对应的索引。 Multiple indexers are also supported. 还支持多个索引器。

i put Indexers of a property in my xaml 我在我的XML中放置了一个属性的索引器

<Image Source="{Binding ImagePathList[0]}" Height="50" Width="50" Grid.Row="0" Grid.Column="0" VerticalAlignment="Top" Margin="0,7,7,0" Grid.RowSpan="2">

i do not give the viewmodel code because i am pretty sure ListImagePathList have data. 我不提供viewmodel代码,因为我很确定ListImagePathList有数据。

EDIT* more detail: ImagePathList[0] is a web image url 编辑*更多详细信息:ImagePathList [0]是一个网络图像网址

EDIT FOR Brendan 编辑布伦丹

model is Article 模特是文章

public class Article : INotifyPropertyChanged
    {
        private long _Id;
        public long ID
        {
            get { return _Id; }
            set
            {
                if (_Id != value)
                {
                    _Id = value;
                    NotifyPropertyChanged();
                }
            }
        }


        private string _subject;
        public string Subject
        {
            get
            {
                return _subject;
            }
            set
            {
                if (_subject != value)
                {
                    _subject = value;
                    NotifyPropertyChanged();
                }
            }
        }

        private string _words;
        public string Words
        {
            get
            {
                return _words;
            }
            set
            {
                if (_words != value)
                {
                    _words = value;
                    NotifyPropertyChanged();
                }
            }
        }

        private DateTime _publishDate;
        public DateTime PublishDate
        {
            get
            { return _publishDate; }
            set
            {
                if (_publishDate != value)
                {
                    _publishDate = value;
                    NotifyPropertyChanged();
                }
            }
        }

        public List<string> ImagePathList = new List<string>();

        private string _firstImage;
        public string FirstImage
        {
            get
            {
                return _firstImage;
            }
            set
            {
                if (_firstImage != value)
                {
                    _firstImage = value;
                    NotifyPropertyChanged();
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

ArticleViewModel is in below; ArticleViewModel在下面; All data returned from network is correct! 从网络返回的所有数据都是正确的!

public class ArticleListViewModel : INotifyPropertyChanged
    {    
        public ArticleListViewModel()
        {
            this.ArticleCollection = new ObservableCollection<Article>();                
        }

        public ObservableCollection<Article> ArticleCollection
        {
            get;
            private set;
        }

        public void LoadPage(int pageNumber)
        {
            if (pageNumber == 1)
            {
                this.ArticleCollection.Clear();
            }

            IsLoading = true;
            ReadArticleList(pageNumber);

        }

        private async void ReadArticleList(int pageNumber)
        {
            try
            {

                List<Article> articleList = new List<Article>();
                articleList = await CollectionHttpClient.GetArticlesByPageAsync(pageNumber);

                this.ArticleCollection.Add(item);

                }

            }
            catch(Exception ex)
            {
                if (ex.HResult == -2146233088 && ex.Message.Equals("Response status code does not indicate success: 404 ()."))
                {
                    MessageBox.Show("The network is not set right. Internet cannot be accessed.");
                }
                else
                {
                    MessageBox.Show("sorry, no data.");
                }

            }

        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }

The XAML code you show is fine. 您显示的XAML代码很好。

There may be a problem with the DataContext . DataContext可能有问题。 Maybe the page DataContext has not been set? 也许尚未设置页面DataContext Or maybe the the DataContext has changed eg inside an ItemTemplate 也许DataContext已更改,例如在ItemTemplate内部

Otherise the problem is probably to do with the bound property. 另一个问题可能与绑定属性有关。 Try the following 尝试以下

private ObservableCollection<string> _imagePathList = new ObservableCollection<string>();
public ObservableCollection<string> ImagePathList {
    get { return this._imagePathList; }
    set {
        if (this._imagePathList != value)
        {
            this._imagePathList = value;
            // I'm going to assume you have the NotifyPropertyChanged
            // method defined on the view-model
            this.NotifyPropertyChanged();
        }
    }
}

ObservableCollection is in System.Collections.ObjectModel and is like List but if elements are added/removed then the PropertyChanged event is fired. ObservableCollectionSystem.Collections.ObjectModel ,与List相似,但是如果添加/删除了元素,则将触发PropertyChanged事件。 Also note that any bound property must have a get associated with it for it to work at all. 另外请注意,任何绑定属性必须有一个get与之相关的它在所有的工作。

Another possibility is that ImagePathList was not assigned to or is empty - in which case, make sure you assign to it! 另一种可能是ImagePathList没有分配给它或为空-在这种情况下,请确保分配给它!

In case you have not yet implemented the NotifyPropertyChanged method, here it is ... 如果您尚未实现NotifyPropertyChanged方法,请在此处...

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

You will also need to add INotifyPropertyChanged interface to the containing class eg 您还需要将INotifyPropertyChanged接口添加到包含的类,例如

public class MyViewModelClass : INoftifyPropertyChanged 
{
    ...
}

I think the problem concerns the place where your images come from. 我认为问题与图片的来源有关。 As it is said at MSDN : 正如在MSDN中所说的:

You can set the Source by specifying an absolute URL (eg http://contoso.com/myPicture.jpg ) or specify a URL relative to the XAP file of your application. 您可以通过指定绝对URL(例如, http : //contoso.com/myPicture.jpg )或指定相对于应用程序XAP文件的URL来设置Source。

You can set this property in XAML, but in this case you are setting the property as a URI. 您可以在XAML中设置此属性,但是在这种情况下,您需要将该属性设置为URI。 The XAML behavior relies on underlying type conversion that processes the string as a URI, and calls the BitmapImage(Uri) constructor. XAML行为依赖于将字符串作为URI处理并调用BitmapImage(Uri)构造函数的基础类型转换。 This in turn potentially requests a stream from that URI and returns the image source object. 反过来,这可能会从该URI请求流,并返回图像源对象。

Just for test - place some images in your project and then set ImagePathList to them. 仅用于测试-将一些图像放入您的项目中,然后将ImagePathList设置为它们。 See if that works (it should as I think). 看看是否可行(我认为应该如此)。 Or see if you can get BitmapImage(ImagePathList); 或者看看是否可以获得BitmapImage(ImagePathList);

It's hard for me to say now (as I don't know how your ImagePathList looks like) what could be a reason of the failure. 我现在很难说(因为我不知道您的ImagePathList是什么样),这可能是失败的原因。 But if I were you, I would test this. 但是如果我是你,我会测试一下。


I would advise to use a property (or you can use converter which will also do the job): 我建议使用一个属性(或者您可以使用转换器来完成此工作):

// a property in your class
public Uri FirstImage
{
   get
   {
        return new Uri(ImagePathList.FirstOrDefault(), UriKind.Absolute);
   }
}

On the other hand if you are downloading images to IsolatedStorage then you will have to use another property, that will load BitmapImage from IS: 另一方面,如果要将图像下载到IsolatedStorage,则必须使用另一个属性,该属性将从IS加载BitmapImage:

public BitmapImage FirstImage // getter - BitmapImage
{
    get
    {
       if (String.IsNullOrEmpty(ImagePath[0])) return null;
       BitmapImage temp = new BitmapImage();

       using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
       using (IsolatedStorageFileStream file = ISF.OpenFile(ImagePath[0], FileMode.Open, FileAccess.Read))
            temp.SetSource(file);
       return temp;
    }
}

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM