I have a page in a Windows Phone 7 app where the user can edit or delete an Transaction object. The Transaction object is an Linq-to-Sql class that have a relationship with
This error may also be caused by the order of the XAML properties:
This does NOT work (throws the exception because the ItemsSource is null when the SelectedItem is set):
<toolkit:ListPicker DisplayMemberPath="Title" SelectionMode="Single"
SelectedItem="{Binding SelectedCategory, Mode=TwoWay}"
ItemsSource="{Binding Categories}" />
This works as the itemssource is initialized first:
<toolkit:ListPicker DisplayMemberPath="Title" SelectionMode="Single"
ItemsSource="{Binding Categories}"
SelectedItem="{Binding SelectedCategory, Mode=TwoWay}" />
ListPicker uses Items.IndexOf to get the index of item instance that it should select.
If the instance does not match (it is not an object instance from the collection) the IndexOf will return -1 and the InvalidOperationException is thrown with the message: "SelectedItem must always be set to a valid value".
Override Equals method of the item type in the collection and it will work as expected.
Example:
public override bool Equals(object obj)
{
var target = obj as ThisType;
if (target == null)
return false;
if (this.ID == target.ID)
return true;
return false;
}
Hope it helps
There are just two checks which throws the InvalidOperationException on SelectedItem
Debugging with watch on listpicker.Items and overridden Equals method will help us identify issue
The problem is that the ListPicker
is expecting the SelectedItem
to be a ListPickerItem
whereas you're binding it to an object of type Transaction
. You can get around the problem by binding to the SelectedIndex
property instead and then select the appropriate object from your ViewModel based on the index.
Also, if the reason you have the Tap
handler defined is because of the bug where the ListPicker
does not open when placed within a ScrollViewer
, take a look at patch ID 10247. If you recompile the toolkit with that patch it fixes the problem.