繁体   English   中英

Xamarin 形式:System.InvalidCastException:“指定的强制转换无效。”

[英]Xamarin forms: System.InvalidCastException: 'Specified cast is not valid.'

我的项目中有一个分组列表视图。 当我尝试为列表视图添加ItemSelected事件时,出现以下错误:

System.InvalidCastException: '指定的转换无效。'

我的代码

XAML:

<ListView
  ItemsSource="{Binding AllItems,Mode=TwoWay}">
    <ListView.GroupHeaderTemplate>
        <DataTemplate>
            <ViewCell>
            //header label
                <Label/>
            </ViewCell>
        </DataTemplate>
    </ListView.GroupHeaderTemplate>
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
            <ViewCell.View>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="40*"/>
                        <ColumnDefinition Width="60*"/>
                    </Grid.ColumnDefinitions>

                    <StackLayout
                        Grid.Column="0"
                        BackgroundColor="#f9f9f9"
                        Orientation="Vertical">

                        //Items
                    </StackLayout>

                        <Label Grid.Column="1"/>
                    </Grid>
                </ViewCell.View>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.Footer>
        <Label/>
    </ListView.Footer>
</ListView>

视图模型

public ObservableCollection<EventsHB> AllItems
{
    get
    {
        return _allItems;
    }
    set
    {
        _allItems = value;
        OnPropertyChanged("AllItems");
    }
}

XAML文件

MyEventsListview.ItemSelected += (object sender, SelectedItemChangedEventArgs e) =>
{
    var selectedItem = (EventsHB) e.SelectedItem;
    if (selectedItem != null)
    {
        //loading the next page
    }
    MyEventsListview.SelectedItem = null;
};

从我的XF 线程中得到了解决方案。

这是因为 EventsHB 是您的组项目,但所选项目是您的组项目的一部分,您无法将其投射到 EventsHB。 IE

// Your EventsHB looks like
public class EventsHB : ObservableCollection<Model>
{
   public string Title { set; get; }
}

那么所选项目的类型是模型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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