绑定ListPicker.SelectedIndex问题 [英] Binding ListPicker.SelectedIndex problem

查看:189
本文介绍了绑定ListPicker.SelectedIndex问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对Windows Phone 7 UserControl中的ListPicker的SelectedIndex属性进行双向绑定.

I'm trying to do a two way binding of the SelectedIndex attribute of a ListPicker in a Windows Phone 7 UserControl.

在设置DataContext时,它引发以下异常: SelectedIndex must always be set to a valid value.

It raises the following exception when I set the DataContext: SelectedIndex must always be set to a valid value.

这是XAML代码

This is the XAML code

<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <toolkit:ListPicker
        Grid.Row="0"
        x:Name="List1"
        SelectionChanged="Picker_SelectionChanged"
        SelectedIndex="{Binding PickerSelectedIndex, Mode=TwoWay}"
        ItemTemplate="{StaticResource PickerTemplate}"
        ItemsSource="{Binding MyList}"/>
</Grid>

以及DataContext中的代码

And the code behind in DataContext

    private ObservableCollection<MyClass> myList = null;
    public ObservableCollection<MyClass> MyList
    {
        get { return this.myList; }
        set
        {
            if (value != this.myList)
            {
                this.myList= value;
                NotifyPropertyChanged("MyList");

                this.PickerSelectedIndex = 0;
            }
        }
    }

    private int pickerSelectedIndex = 0;
    public int PickerSelectedIndex
    {
        get
        {
            return this.pickerSelectedIndex;
        }
        set
        {
            this.pickerSelectedIndex= value;
        }
    }

PickerSelectedIndex.get中放置一个断点我可以看到它已正确返回(0). 我确定问题是SelectedIndex="{Binding PickerSelectedIndex, Mode=TwoWay}",因为删除此行可以解决问题,并且我可以看到ListPicker正确加载了MyList中的数据.

Putting a breakpoint in PickerSelectedIndex.get I can see that it is returned correctly (0). I am sure that the problem is SelectedIndex="{Binding PickerSelectedIndex, Mode=TwoWay}" because deleting this line solves the problem, and I can see the ListPicker correctly loaded with the data from MyList.

我看不出问题出在哪里...

I can't see where is the problem...

推荐答案

ItemsSource解决后,移动SelectedIndex.

这是有效的代码段

<toolkit:ListPicker
    Grid.Row="0"
    x:Name="List1"
    SelectionChanged="Picker_SelectionChanged"
    ItemTemplate="{StaticResource PickerTemplate}"
    ItemsSource="{Binding MyList}"
    SelectedIndex="{Binding PickerSelectedIndex, Mode=TwoWay}"/>

有人对此有解释吗?

这篇关于绑定ListPicker.SelectedIndex问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆