Get value of Xamarin Forms Custom Rendered Checkbo

2019-09-03 06:34发布

问题:

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.