Samstag, 24. November 2012

Windows Phone 8–ListPicker SelectedItem not bindable

At this week the ListPicker is the second control with issues for binding the SelectedItem property (see http://dotnet-redzone.blogspot.de/2012/11/windows-phone-8longlistselector.html). At this time I tried a second problem solution and made the SelectedIndex my binding property. In my Viewmodel I have to define therefore a method which maps my SelectedIndex to the instance in my list which is populated in the ListPicker (the WorkTasks ObservableCollection):

private int GetWorkTaskIndexFromId(string id)
        {
            for (int index = 0; index < this.WorkTasks.Count; index++)
            {
                if (this.WorkTasks[index].UniqueId == id)
                {
                    return index;
                }
            }

            return 0;
        }

My property for the SelectedIndex in the ViewModel looks like this:

       public int SelectedWorkTaskIndex
        {
            get
            {
                return _selectedWorkTaskIndex;
            }

            set
            {
                _selectedWorkTaskIndex = value;
                if (_allowedToChangeValue && _selectedWorkTaskIndex >= 0)
                {
                    this.SelectedEntry.WorkTask = WorkTasks[value];
                }

                this.RaisePropertyChanged("SelectedWorkTaskIndex");
            }
        }

The last step was to set the SelectedWorkTaskIndex corerctly after loading the instance of my ViewModel connected model. This is done in my implementation of the LoadWorkTask RelayCommand:

        private void LoadWorkTaskList()
        {
            try
            {
                 ....
                
               _allowedToChangeValue = true;

                SetWorkTask();
               
            }
            catch (Exception error)
            {
               .....
            }
        }
        private void SetWorkTask()
        {
            if (SelectedEntry.WorkTask != null)
            {
                SelectedWorkTaskIndex = this.GetWorkTaskIndexFromId(SelectedEntry.WorkTask.UniqueId);
            }
            else
            {
                if (WorkTasks != null && WorkTasks.Count > 0)
                {
                    SelectedWorkTaskIndex = 0;
                }
            }
        }

2 Kommentare:

  1. The SelectedItem does work fine... but you need to set the mode=TwoWay.

    I first had the same problem as you have, but then I retried it with mode=TwoWay and that worked fine.

    AntwortenLöschen
    Antworten
    1. I set the mode already to TwoWay, but in my case I have still this problem.

      Löschen