WP8 - 如何按所选项目更改MapCartographicMode

时间:2014-03-22 12:27:42

标签: c# xaml windows-phone-8

我有这个列表框:

<ListBox x:Name="layerMenu" SelectionChanged="layerMenu_SelectionChanged" >
        <ListBoxItem Content="Road" HorizontalAlignment="Center"/>
        <ListBoxItem Content="Aerial" HorizontalAlignment="Center" />
        <ListBoxItem Content="Hybrid" HorizontalAlignment="Center" />
        <ListBoxItem Content="Terrain" HorizontalAlignment="Center" />
</ListBox>

我想更改地图的制图模式。以下不起作用。

private void layerMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
{    
     MapCartographicMode selected = (MapCartographicMode)((sender as ListBox).SelectedItem);
     MyMap.CartographicMode = selected;
}

发生此错误:

System.InvalidCastException: Specified cast is not valid.

我可以通过使用开关(layerMenu.SelectedIndex)来解决这个问题,但如果可能,我更喜欢这种更短的方式。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

更改此

MapCartographicMode selected = (MapCartographicMode)((sender as ListBox).SelectedItem);
MyMap.CartographicMode = selected;

到此:

ListBox listbox = (sender as ListBox)
ListBoxItem item = (ListBoxitem)listbox.SelectedItem;
MapCartographicMode selected = (MapCartographicMode)Enum.Parse(typeof(MapCartographicMode), item.Content.ToString());      
MyMap.CartographicMode = selected;