Using ListPicker and DataBinding

2019-07-15 19:55发布

问题:

Ok. I give up. I want to use ListPicker control in one of my Windows Phone apps. I am getting an Exception SelectedItem must always be set to a valid value.

This is my XAML piece of ListPicker:

<toolkit:ListPicker x:Name="CategoryPicker"                                     
           FullModeItemTemplate="{StaticResource CategoryPickerFullModeItemTemplate}" 
           Margin="12,0,0,0"                                    
           ItemsSource="{Binding CategoryList}"                                        
           SelectedItem="{Binding SelectedCategory, Mode=TwoWay}"
           ExpansionMode="ExpansionAllowed"      
           FullModeHeader="Pick Categories" 
           CacheMode="BitmapCache" 
           Width="420" 
           HorizontalAlignment="Left" />

CategoryList is an ObservableCollection<Category> in my ViewModel. SelectedCategory is a property in my ViewModel of type Category.

This is how I am declaring both CategoryList and SelectedCategory:

private Category _selectedCategory;// = new Category();


        private ObservableCollection<Category> _categoryList = new ObservableCollection<Category>();

        public ObservableCollection<Category> CategoryList
        {
            get
            {
                return _categoryList;
            }

            set
            {
                _categoryList = value;
                RaisePropertyChanged("CategoryList");
            }
        }


        public Category SelectedCategory
        {
            get
            {
                 return _selectedCategory;
            }
            set
            {
                if (_selectedCategory == value)
                {
                    return;
                }
                _selectedCategory = value;

                RaisePropertyChanged("SelectedCategory");
            }
        }

Appreciate your help!!! Maybe I have not understood the usage of ListPicker very well.

回答1:

Take a look at my answer to this question: Silverlight ComboBox binding with value converter

The short answer is that the selected item must be an item that is contained within the collection. Your getter is setting the selected item to a new object. This new object is not contained within the collection



回答2:

I'd expect the object returned by SelectedCategory to be one of the objects from the CategoryList collection. In your example you are instanciating it within the get, so this is definitely not the case.

If CategoryList contains some values, then perhaps initialize _selectedCategory to null, and then in the get

if(_selectedCategory == null) {
   _selectedCategory = CategoryList.First();
}