简体   繁体   English

未处理的异常:System.InvalidCastException:指定的强制转换无效。 Xamarin中发生错误

[英]Unhandled Exception: System.InvalidCastException: Specified cast is not valid. occurred ERROR in Xamarin

I have a SwitchCell implemented within a ListView; 我在ListView中实现了SwitchCell; I want to be able to access the properties of the SwitchCell: On and text. 我希望能够访问SwitchCell的属性:On和text。 I want to be able to get and set the OnProperty of the SwitchCell to change/read the Switch state from within the xaml.cs class. 我希望能够获取并设置SwitchCell的OnProperty来从xaml.cs类中更改/读取Switch状态。

when I run the code, I get the Unhandled Exception error. 运行代码时,出现未处理的异常错误。 i am very new to both Xamarin and C# so any help/advise/examples of solving the problem will be greatly appreciated. 我对Xamarin和C#都是陌生的,因此对解决问题的任何帮助/建议/示例将不胜感激。

The exception is happening at var selectedItem = ((SwitchCell)sender).BindingContext as Relays; 异常发生在var selectedItem =((SwitchCell)sender).BindingContext作为中继; in the SwitchCell.xaml.cs. 在SwitchCell.xaml.cs中。

My Relay.cs class is as follows: 我的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

      }
   }

My SwitchCell.xaml is as follows: 我的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>

My SwitchCell.xaml.cs is as follows: 我的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;
            }

            }

        }       

    }

}

This is the error I get in VS 2017: Unhandled Exception: System.InvalidCastException: Specified cast is not valid. 这是我在VS 2017中遇到的错误: 未处理的异常:System.InvalidCastException:指定的强制转换无效。 occurred . 发生了

I am not sure if this is useful but this is what I get from the Call Stack : 我不确定这是否有用,但这是我从调用堆栈中得到的:

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

I have no idea what I am doing wrong. 我不知道我在做什么错。 Any help will be appreciated. 任何帮助将不胜感激。 Thanks. 谢谢。

Only cast that seems to happen is here: var selectedItem = ((SwitchCell)sender).BindingContext as Relays; 这里似乎只发生了var selectedItem = ((SwitchCell)sender).BindingContext as Relays;var selectedItem = ((SwitchCell)sender).BindingContext as Relays;

Check if sender is indeed a SwitchCell . 检查sender是否确实是SwitchCell

It turns out it was my naming. 原来那是我的名字。 Thank you for all your help @Gerald Versluis and for your suggestion @Benl. 感谢您对@Gerald Versluis的所有帮助和对@Benl的建议。

暂无
暂无

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

相关问题 Xamarin 形式:System.InvalidCastException:“指定的强制转换无效。” - Xamarin forms: System.InvalidCastException: 'Specified cast is not valid.' 在 xamarin 项目 System.InvalidCastException:“指定的演员表无效。” - in xamarin project System.InvalidCastException: 'Specified cast is not valid.' System.InvalidCastException:&#39;指定的强制转换无效。 - System.InvalidCastException: 'Specified cast is not valid.' System.InvalidCastException:指定的强制转换无效。错误 - System.InvalidCastException: Specified cast is not valid. Error System.InvalidCastException:指定的强制转换无效。 -DynamoDB查询 - System.InvalidCastException: Specified cast is not valid. - DynamoDB Query System.InvalidCastException:“指定的演员表无效。” C# MYSQL - System.InvalidCastException: 'Specified cast is not valid.' C# MYSQL Xamarin 表单与 Firebase。 数据检索抛出 System.InvalidCastException: &#39;指定的转换无效。&#39; - Xamarin Forms with Firebase. Data retrival throwing System.InvalidCastException: 'Specified cast is not valid.' Xamarin forms: System.InvalidCastException: '指定的转换无效 - Xamarin forms: System.InvalidCastException: 'Specified cast is not valid XML文件错误错误:System.InvalidCastException:指定的强制转换无效 - XML File Error Error : System.InvalidCastException: Specified cast is not valid 指定的转换无效-System.InvalidCastException - Specified cast is not valid - System.InvalidCastException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM