首页 > 解决方案 > 未处理的异常:System.InvalidCastException:指定的转换无效。Xamarin 发生错误

问题描述

我在 ListView 中实现了 SwitchCell;我希望能够访问 SwitchCell: On 和 text 的属性。我希望能够获取和设置 SwitchCell 的 OnProperty 以从 xaml.cs 类中更改/读取 Switch 状态。

当我运行代码时,我得到了 Unhandled Exception 错误。我对 Xamarin 和 C# 都很陌生,所以任何解决问题的帮助/建议/示例将不胜感激。

异常发生在var selectedItem = ((SwitchCell)sender).BindingContext as Relays; 在 SwitchCell.xaml.cs 中。

我的 Relay.cs 类如下:

using System;
using System.Collections.Generic;
using System.Text;

namespace Socket.Models
{
    public class Relays
    {
      public Boolean isOn { get; set; }       // Set the state of the 
                                                switch 

      public string State { get; set; }       // Get the state of the 
                                     switch based on the isOn property

      public string Name { get; set; }        // Set the name of the 
                                               relay in the list

      }
   }

我的 SwitchCell.xaml 如下:

  <?xml version="1.0" encoding="utf-8" ?>
      <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Socket.SwitchCell"
         Title="Relay Control Page">

<ContentPage.Content>
    <StackLayout Padding="10,0,0,0">

        <ListView x:Name="lstView" SelectionMode="None">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <SwitchCell x:Name="Sw1" Text="{Binding Name}" On=" 
                             {Binding isOn, Mode=TwoWay}" 
                                OnChanged="SwitchCell_OnChanged_2"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        </StackLayout>
    </ContentPage.Content>
</ContentPage>

我的 SwitchCell.xaml.cs 如下:

  using Socket.Models;
  using System;
  using System.Collections.Generic;
  using System.Collections.ObjectModel;
  using System.ComponentModel;
  using System.Linq;
  using System.Runtime.CompilerServices; 
  using System.Text;
  using System.Threading.Tasks;
  using Xamarin.Forms;
  using Xamarin.Forms.Xaml;

namespace Socket
{
    [XamlCompilation(XamlCompilationOptions.Compile)]

public partial class SwitchCell : ContentPage
{

    public SwitchCell ()
    {
        InitializeComponent ();
        loadSampleData();
    }

    private void loadSampleData()
    {
        // Create sample data

        ObservableCollection<Relays> listRelays = new 
          ObservableCollection<Relays>();

        listRelays.Add(new Relays { Name ="Relay 1", State = "", 
                 isOn=false });
        listRelays.Add(new Relays { Name ="Relay 2", State = "", 
                 isOn=false });
        listRelays.Add(new Relays { Name ="Relay 3", State = "", 
                 isOn=false });

        lstView.ItemsSource = listRelays;

    }

    private void SwitchCell_OnChanged_2(object sender, ToggledEventArgs 
                                                                e)
    {
        var selectedItem = ((SwitchCell)sender).BindingContext as 
                                        Relays;

        if (true)
        {            
            bool IsToggled = e.Value;
            string name = IsToggled.ToString();

            if (name == "True")
            {
                //DisplayAlert("ON", "Relay 1 On", "Cancel");
                BackgroundColor = Color.Silver;

                if (selectedItem.isOn == false)
                {
                    BackgroundColor = Color.Gold;
                    selectedItem.Name = "Changed";
                }
            }

            else
            {
                //DisplayAlert("OFF", "Relay 1 OFF", "Cancel");
                BackgroundColor = Color.LightSkyBlue;
            }

            }

        }       

    }

}

这是我在 VS 2017 中遇到的错误:Unhandled Exception: System.InvalidCastException: Specified cast is not valid。发生

我不确定这是否有用,但这是我从调用堆栈中得到的:

C:\Users\ryno\Desktop\Xamarin\Socket\Socket\Socket\SwitchCell.xaml.cs:42,13 的 Socket.SwitchCell.SwitchCell_OnChanged_2 中的 0x1。

我不知道我做错了什么。任何帮助将不胜感激。谢谢。

标签: c#listviewxamarinxamarin.forms

解决方案


只有似乎发生的演员在这里:var selectedItem = ((SwitchCell)sender).BindingContext as Relays;

检查是否sender确实是SwitchCell.


推荐阅读