簡體   English   中英

從Xamarin.Android中的單擊事件處理程序訪問CheckBox屬性

[英]Accessing CheckBox property from click event handler in Xamarin.Android

如果我像這樣編寫事件處理程序:

CheckBox whatever = FindViewById<CheckBox> (Resource.Id.checkBox1);
whatever.Click += (s, e) =>
{
    if (!whatever.Checked)
    {
    //do stuff
    }
}

調用處理程序時拋出異常。 如果我為具有不同名稱的同一視圖創建另一個CheckBox對象,如下所示:

CheckBox whatever = FindViewById<CheckBox> (Resource.Id.checkBox1);
whatever.Click += (s, e) =>
{
    CheckBox whatever2 = FindViewById<CheckBox> (Resource.Id.CheckBox1);
    if (!whatever2.Checked)
    {
    //do stuff
    }
}

沒有問題。 為什么需要重復的對象?

如果checkBox1和CheckBox1不匹配是一個錯字,這是一個奇怪的問題。 無論如何,您最好使用CheckedChanged事件。 所有下面的場景都運行得很好,所以代碼中可能還有其他東西不匹配。 布局上的Id是checkBox1還是CheckBox1?

        var checkBox = FindViewById<CheckBox>(Resource.Id.CheckBox1);

        checkBox.CheckedChange += (sender, args) =>
        {
            if (!args.IsChecked)
            {

            }
        };

        checkBox.Click += (sender, args) =>
        {
            if (!checkBox.Checked)
            {

            }

            if (!((CheckBox)sender).Checked)
            {

            }
        };

你用什么方法分配什么控件?

protected override void OnResume()
{
    base.OnResume();

    CheckBox whatever = FindViewById<CheckBox>(Resource.Id.checkBox1);
    if (whatever != null) //Verify the state of your whatever object to avoid exception
    {
        whatever.Click += (s, e) =>
        {
            if (!whatever.Checked)
            {
                //do stuff
            }
        };
    }
}

我總是在OnResume事件中聲明我的控件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM