首页 文章

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

提问于
浏览
0

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

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

例外情况发生在SwitchCell.xaml.cs的 var selectedItem = ((SwitchCell)sender).BindingContext as Relays; .

我的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. occurred .

我不确定这是否有用,但这是我从 Call Stack 得到的:

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

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

2 回答

  • 1

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

    检查 sender 是否确实是 SwitchCell .

  • 0

    原来这是我的命名 . 感谢您对@Gerald Versluis的所有帮助以及@Benl的建议 .

相关问题