简体   繁体   中英

WP8 ListPicker Bind

When I bind my data via item source to my ListPicker :

C#:

var sightingTypes = SightingTypes.List;
sightingTypesPicker.ItemsSource = sightingTypes;

XML:

    <toolkit:ListPicker x:Name="sightingTypesPicker" ItemsSource="{Binding sightingTypes, ElementName=this}">
        <toolkit:ListPicker.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Name}" FontSize="{StaticResource PhoneFontSizeSmall}"/>
                </StackPanel>
            </DataTemplate>
        </toolkit:ListPicker.ItemTemplate>
    </toolkit:ListPicker>

I can see the Name being shown in the ListPicker, but, when I click on the ListPicker it shows the List of the Object Type, like this:

MyProject.Model.SightingType
MyProject.Model.SightingType
MyProject.Model.SightingType
MyProject.Model.SightingType
MyProject.Model.SightingType
MyProject.Model.SightingType

How do I:

A: Make the Name Property show when the list shows

B: Bind the ID Property as the Value but not show it

You need to assign FullModeItemTemplate for that to work:

<toolkit:ListPicker x:Name="sightingTypesPicker" ItemsSource="{Binding sightingTypes, ElementName=this}">
    <toolkit:ListPicker.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Name}" FontSize="{StaticResource PhoneFontSizeSmall}"/>
            </StackPanel>
        </DataTemplate>
    </toolkit:ListPicker.ItemTemplate>
    <toolkit:ListPicker.FullModeItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Name}" FontSize="{StaticResource PhoneFontSizeSmall}"/>
                <TextBlock Text="{Binding SomeOtherProp}" FontSize="{StaticResource PhoneFontSizeSmall}"/>
            </StackPanel>
        </DataTemplate>
    </toolkit:ListPicker.FullModeItemTemplate>
</toolkit:ListPicker>

EDIT : To answer your question B: You can use the SelectedItem DependencyProperty to get the instance of the selected object:

With MVVM approach:

<toolkit:ListPicker x:Name="sightingTypesPicker" 
                    ItemsSource="{Binding SightingTypes}"
                    SelectedItem="{Binding SelectedSigntingType, Mode=TwoWay}">

With code-behind approach:

sightingTypesPicker.SelectionChanged += (s, e) => {
    MessageBox.Show(((SightingType)e.AddedItems[0]).ID);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM