【问题标题】:Xamarin forms: System.InvalidCastException: 'Specified cast is not valid.'Xamarin 形式:System.InvalidCastException:“指定的强制转换无效。”
【发布时间】:2020-07-01 08:41:27
【问题描述】:

我的项目中有一个分组列表视图。当我尝试为列表视图添加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.CS

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

【问题讨论】:

  • 你能在调试器中看到SelectedItem是什么吗?
  • @Miamy At that line app break with this exception
  • 所以你应该在这一行下一个断点并查看变量值
  • @Miamy 得到了解决方案,我已将其添加为我的答案。

标签: c# listview xamarin xamarin.forms


【解决方案1】:

从我的XF thread 获得解决方案。

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

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

那么选中项的类型就是Model。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 2013-08-27
    相关资源
    最近更新 更多