亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

未處理的異常:System.InvalidCastException:指定的強制轉換無效。

未處理的異常:System.InvalidCastException:指定的強制轉換無效。

C#
郎朗坤 2021-10-24 19:57:45
我在 ListView 中實現了一個 SwitchCell;我希望能夠訪問 SwitchCell 的屬性:On 和 text。我希望能夠獲取和設置 SwitchCell 的 OnProperty 以從 xaml.cs 類中更改/讀取 Switch 狀態。當我運行代碼時,我收到未處理的異常錯誤。我對 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>這是我在 VS 2017 中遇到的錯誤:未處理的異常:System.InvalidCastException:指定的強制轉換無效。發生了。我不確定這是否有用,但這是我從調用堆棧中得到的:位于 C:\Users\ryno\Desktop\Xamarin\Socket\Socket\Socket\SwitchCell.xaml.cs 的 Socket.SwitchCell.SwitchCell_OnChanged_2 中的 0x1:42,13。我不知道我做錯了什么。任何幫助將不勝感激。謝謝。
查看完整描述

2 回答

?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

只有似乎發生的演員在這里: var selectedItem = ((SwitchCell)sender).BindingContext as Relays;

檢查是否sender確實是SwitchCell.


查看完整回答
反對 回復 2021-10-24
?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

原來這是我的名字。感謝您對@Gerald Versluis 的所有幫助以及@Benl 的建議。


查看完整回答
反對 回復 2021-10-24
  • 2 回答
  • 0 關注
  • 571 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號