Using ListPicker and DataBinding

放肆的年华 提交于 2020-01-04 19:42:20

问题


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


来源:https://stackoverflow.com/questions/9745279/using-listpicker-and-databinding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!