WP8 ListPicker Bind

那年仲夏 提交于 2020-01-14 03:59:08

问题


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


回答1:


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);
};


来源:https://stackoverflow.com/questions/18301957/wp8-listpicker-bind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!