简体   繁体   English

从Xamarin.Android中的单击事件处理程序访问CheckBox属性

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

If I write the event handler like this: 如果我像这样编写事件处理程序:

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

an exception is thrown when the handler is called. 调用处理程序时抛出异常。 If I create another CheckBox object for the same view with a different name- like this: 如果我为具有不同名称的同一视图创建另一个CheckBox对象,如下所示:

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

there are no issues. 没有问题。 Why is the duplicate object required? 为什么需要重复的对象?

That is a weird issue if the checkBox1 & CheckBox1 mismatch is a typo. 如果checkBox1和CheckBox1不匹配是一个错字,这是一个奇怪的问题。 In any case you might be better of using the CheckedChanged event. 无论如何,您最好使用CheckedChanged事件。 All the below scenarios run just fine so there's probably something else in the code that doesn't match. 所有下面的场景都运行得很好,所以代码中可能还有其他东西不匹配。 Is the Id on the layout checkBox1 or CheckBox1? 布局上的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)
            {

            }
        };

In what method you assign the whatever control? 你用什么方法分配什么控件?

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
            }
        };
    }
}

I always declare my controls inside OnResume event. 我总是在OnResume事件中声明我的控件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM