2017-06-15 70 views
0

我是Xamarin的新手,我有兩個字符串的列表,並且我想比較小寫列表中的元素是否與小寫字母的元素相同。Xamarin字符串列表和標籤之間的比較文本

當我添加.ToLower()到一個標籤的元素,調試停止,我不知道爲什麼。

這裏是我的代碼:

Dictionary<int, string> WordsList = new Dictionary<int, string>(); 
Dictionary<int, string> WordsList2 = new Dictionary<int, string>(); 

public TestWords() 
{ 
    InitializeComponent(); 

    mywordsdatabase = new MyWordsDatabase(); 

    var mywords = mywordsdatabase.GetWords(); 

    int i = 0; 

    // TestAnswer.IsVisible = false; 
    foreach (var myword in mywords) 
    { 
     WordsList[i] = myword.Word1; 
     WordsList2[i] = myword.Word2.ToLower(); // this is ok 

     i++; 
    } 

    word10.Text = WordsList[0]; 
    word11.Text = WordsList[1]; 

    word20.Focus(); 
    word21.Focus(); 
} 

//Correction for the test 
void OnOKTest(object sender, EventArgs args) 
{ 
    int yes = 0; 
    int no = 0; 

    //############ if == ############# 
    if (WordsList2[0] == word20.Text.ToLower()) // but this is not accepted 
    { 
     true0.Text = "✔"; 
     yes++; 
    } 

    if (WordsList2[1] == word21.Text.ToLower()) // but this is not accepted 
    { 
     true1.Text = "✔"; 
     yes++; 
    } 
} 

這是我的XAML:

<Grid VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Padding="5"> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="*" /> 
     <RowDefinition Height="*" /> 
    </Grid.RowDefinitions> 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition Width="*" /> 
     <ColumnDefinition Width="*" /> 
    </Grid.ColumnDefinitions> 

    <Label x:Name="word10" Text="Your Text" FontSize="20" Grid.Row="0" Grid.Column="0" /> 
    <Label x:Name="word11" Text="Your Text" FontSize="20" Grid.Row="1" Grid.Column="0" /> 
    <Entry x:Name="word20" Placeholder="The word traduction" FontSize="20" Grid.Row="0" Grid.Column="2" ></Entry> 
    <Entry x:Name="word21" Placeholder="The word traduction" FontSize="20" Grid.Row="1" Grid.Column="2" ></Entry> 
    <Label x:Name="true0" Text="" FontSize="20" Grid.Row="0" Grid.Column="3" /> 
    <Label x:Name="true1" Text="" FontSize="20" Grid.Row="1" Grid.Column="3" /> 
</Grid> 

感謝

+0

「未接受」是什麼意思?它是否會產生編譯錯誤?運行時異常? – Jason

+0

檢查myword.Word2是否是一個字符串.. – Atul

+0

@Atul myword.Word2是一個字符串 – hugo

回答

1

你的問題似乎是你對空對象使用ToLower()

更改Ifs到這樣的事情:

if (string.Equals (WordsList2.ElementAtOrDefault (0), word20.Text, StringComparison.InvariantCultureIgnoreCase)) 
{ 
} 

if (string.Equals (WordsList2.ElementAtOrDefault (1), word21.Text, StringComparison.InvariantCultureIgnoreCase)) 
{ 
} 

使用string.Equals是一種更好的方法來比較字符串,你可以定義不同的方法來驗證。

StringComparison.InvariantCultureIgnoreCase這個你不必明確地將它轉換爲小寫。

隨着ElementAtOrDefault你防止發生和IndexOutOfBounds異常,因爲如果索引指定它將返回默認值,而你的情況爲strings德默認值是NULL有沒有項目。要使用此功能,您需要添加using System.Linq

+0

謝謝你在Xamarin中進行了一些修改; if(string.Equals(WordsList2 [0],word20.Text,StringComparison.CurrentCultureIgnoreCase)){} – hugo

0

我不知道什麼叫 「不接受」,但默認的意思Entry組件的Text屬性的值爲null。確保它在調用ToLower()之前有一個值。

+0

我使用「word20.Focus();」來獲得輸入的值 – hugo