0
votes

I have a custom control derived from StackLayout that contains two Labels. Each Label's Text property is bound to a property in the codebehind

public string Label1Text
{
    get { return _label1Text; }
    set
    {
        _label1Text = value;
        OnPropertyChanged(nameof(Label1Text));
    }
}

The text content for the labels is determined by the content of a separate BindableProperty in the codebehind that is set by the consumer of the control, so the properties that the Label's are bound to should not really be visible outside of the custom control.

If I set the properties as private in the codebehind the binding in the Xaml of the control doesn't work. However when set to public they are visible in Intellisense which is wrong as they are for internal use only.

I can set the attributes

[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]

on the properties but is this the correct way to handle this as it only hides the properties not actually preventing them from being set by the consumer of the control?

1
If it is possible for you to share an example which can reproduce this it would make it answering your question that much easier!FreakyAli

1 Answers

1
votes

You could directly create binding between Label.Text and the property of viewmodel .

And define the private property just for internal use inside the custom control .

ViewModel

public class Model
{
    public string TextA { get; set; }
    public string TextB { get; set; }
}

Page

//code behind
public Page2()
    {
        InitializeComponent();

        Model model = new Model
        {
            TextA = "ABCD",
            TextB = "1234"
        };

        this.BindingContext = model;
    }

//xaml
<ContentPage.Content>
    <local:MyStack />
</ContentPage.Content>

Custom control

 //code behind
 public partial class MyStack : ContentView
    {
        private string A { get; set; }   //internal use 
        private string B { get; set; }   //internal use 
        public MyStack()
        {
            InitializeComponent();
            this.BindingContextChanged += MyStack_BindingContextChanged;
        }

        private void MyStack_BindingContextChanged(object sender, EventArgs e)
        {
            var model = this.BindingContext as Model;

            A = model.TextA;
            B = model.TextB;
        }
    }

//xaml
 <ContentView.Content>
        <StackLayout>
            <Label Text="{Binding A}" TextColor="Red"/>
            <Label  Text="{Binding B}" TextColor="Green"/>
        </StackLayout>
  </ContentView.Content>