Listpicker error SelectedItem must always be set to a valid value

后端 未结 4 1055
-上瘾入骨i
-上瘾入骨i 2020-12-16 02:38

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

相关标签:
4条回答
  • 2020-12-16 02:54

    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}" />
    
    0 讨论(0)
  • 2020-12-16 02:56

    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

    0 讨论(0)
  • 2020-12-16 02:57

    There are just two checks which throws the InvalidOperationException on SelectedItem

    1. Listpicker Items is null (Declarative: Order of attributes matters. if selecteditem must appear after itemsource (Programatic: make sure itemsource is loaded)
    2. Listpicker applies Indexof on Items to set selected item. So make sure you override Equals if necessary.

    Debugging with watch on listpicker.Items and overridden Equals method will help us identify issue

    0 讨论(0)
  • 2020-12-16 03:02

    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.

    0 讨论(0)
提交回复
热议问题