Get value of Xamarin Forms Custom Rendered Checkbox

瘦欲@ 提交于 2020-01-07 05:07:10

问题


I have a Checkbox view rendering properly in Xamarin Forms:

public class CheckBoxRenderer : ViewRenderer<LegalCheckbox, CheckBox>
    {
        protected override void OnElementChanged(ElementChangedEventArgs<LegalCheckbox> e)
    {
        base.OnElementChanged (e);
        CheckBox control = new Android.Widget.CheckBox(this.Context);
        control.Checked = false;
        control.Text = "I agree to terms";
        control.SetTextColor (Android.Graphics.Color.Rgb (60, 60, 60));
        this.SetNativeControl(control);
    }
}

I want to check whether or not this checkbox is checked or not. Is there a way I can do this? Do I need to use dependency service?


回答1:


Dont think Dependency Services is going to help here its just an IOC container. Faced with the same issue I'd likely just set up some eventing

public class CheckBoxRenderer : ViewRenderer<LegalCheckbox, CheckBox>
{
    private LegalCheckbox legalCheckBox;
    protected override void OnElementChanged (ElementChangedEventArgs<LegalCheckbox> e)
    {
        base.OnElementChanged (e);
        legalCheckBox = e.NewElement;
        CheckBox control = new Android.Widget.CheckBox(this.Context);
        control.Checked = false;
        control.Text = "I agree to terms";
        control.SetTextColor (Android.Graphics.Color.Rgb (60, 60, 60));
        base.SetNativeControl(control);
        Control.Click+=(sender,evt)=> 
            legalCheckBox.Checked = ((CheckBox)sender).Checked;
    }
}

likewise adding a prop to my View

public class LegalCheckbox : View
{
    public bool Checked { 
        get; 
        set; 
    }
    public LegalCheckbox ()
    {
    }
}

Why? I tend to think of the relationship between the Platform controls and the Xamarin Controls as a Model-View-Adapter pattern. The Platform Controls are your View. Your Xamarin Controls are your Model and your renderer does the Adaptations between. To accomplish this we need somewhere in LegalCheckbox(Model) to store the Data we want to collect. Then we have to wire it up so that changes to the View cause changes to the model. Thus we add in the EventHandler for the OnClick event in the View to update our model.

It might appear at initial glace that all of this happens during the OnelementChanged Event. However its only actually wired up during at that point the actual Checked Event wont fire till long after OnElementChanged has completed and its resources been destroyed. Thus we need a reference to our LegalCheckbox out side of the OnElementChanged Event Handler that will still be there when the Clicked event fires.



来源:https://stackoverflow.com/questions/33221234/get-value-of-xamarin-forms-custom-rendered-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!