【问题标题】:Unhandled Exception: System.InvalidCastException: Specified cast is not valid. occurred ERROR in Xamarin未处理的异常:System.InvalidCastException:指定的转换无效。 Xamarin 发生错误
【发布时间】:2019-01-01 05:43:56
【问题描述】:

我在 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 中遇到的错误:未处理的异常: System.InvalidCastException:指定的强制转换无效。发生

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

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

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

【问题讨论】:

  • 调试器应该告诉你是哪一行导致了异常。或者,它是在页面加载时立即发生,还是仅在您执行某项操作后发生?
  • 你能复制并粘贴错误和堆栈跟踪吗?这应该会有所帮助
  • 尝试将页面类(在 xaml 和代码隐藏中)重命名为 SwitchCell 以外的其他名称...(可能与 XAML ListView SwitchCell 控件发生名称冲突)
  • 发生在这一行 var selectedItem = ((SwitchCell)sender).BindingContext as Relays。抱歉,我忘了把这个添加到问题中。
  • @Benl,我会尝试重命名页面,谢谢

标签: c# listview xamarin xamarin.forms


【解决方案1】:

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

检查sender 是否确实是SwitchCell

【讨论】:

  • 我该怎么做?抱歉,我对 C# 很陌生。我在这个 stackoverflow post 中找到了有问题的行作为答案
  • 在该行放置一个断点并将鼠标悬停在sender 变量上以查看它是什么类型的对象。
  • 发件人是:发件人 {Xamarin.Forms.SwitchCell}。这有用吗? var selectedItem 为 null,为什么会发生这种情况?
  • 奇怪。所以,检查出来。 BindingContext 属性呢?那是Relays吗?
  • 是否有一种特定的方式来查看它,因为它没有分配任何“价值”,或者您是在问继电器指的是什么?
【解决方案2】:

原来是我的名字。感谢@Gerald Versluis 的所有帮助以及@Benl 的建议。

【讨论】:

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