Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Data binding controls in C# code

i have been searching for data binding but instead of being in xaml i am searching for being in .cs file, is there a manner (property) that allows me to bind the specific property to a variable?

Best Answers

Answers

  • JarvanJarvan Member, Xamarin Team Xamurai

    i am searching for being in .cs file, is there a manner (property) that allows me to bind the specific property to a variable

    Try to use SetBinding method to achieve this.

    public partial class Page1 : ContentPage
    {
        public Page1()
        {
            InitializeComponent();
    
            ListView listView = new ListView();
            listView.SeparatorVisibility = SeparatorVisibility.None;
    
            ObservableCollection<model_class> models = new ObservableCollection<model_class>();
            models.Add(new model_class { });
    
            listView.ItemsSource = models;
            listView.ItemTemplate = new DataTemplate(typeof(CustomViewCell));
        }
    }
    
    public class CustomViewCell : ViewCell
    {
        public CustomViewCell()
        {
            StackLayout layout = new StackLayout() { Padding = new Thickness(2, 15) };
            layout.Orientation = StackOrientation.Horizontal;
            Label nameLabel = new Label() { HorizontalOptions = LayoutOptions.CenterAndExpand };
            nameLabel.SetBinding(Label.TextProperty, "name");
            nameLabel.SetBinding(Label.TextColorProperty, "color");
            layout.Children.Add(nameLabel);
            View = layout;
        }
    }
    
    public class model_class : INotifyPropertyChanged
    {
        private string _name;
        private Color _color;
    
        public string name { get { return _name; } set { OnPropertyChanged(); _name = value; } }
        public Color color { get { return _color; } set { OnPropertyChanged(); _color = value; } }
    
        public event PropertyChangedEventHandler PropertyChanged;
        void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

    Refer to: https://github.com/xamarin/xamarin-forms-samples/blob/master/UserInterface/ListView/SwitchEntryTwoBinding/twoWayBinding/twoWayBinding/View/HomeCode.cs

  • AndresQuiValAndresQuiVal Member ✭✭

    @Jarvan How does SetBinding works?, i have read docs about it but i just dont understand why a string as second param and why the first param, can you explain me please?

  • JoeMankeJoeManke USMember ✭✭✭✭✭
    edited October 2019

    First is the property on the view you are setting, then the name of the property on the model you are binding to.

    This C# code

    Label nameLabel = new Label() { HorizontalOptions = LayoutOptions.CenterAndExpand };
    nameLabel.SetBinding(Label.TextProperty, "name");
    nameLabel.SetBinding(Label.TextColorProperty, "color");
    

    is equivalent to this XAML

    <Label
        HorizontalOptions="CenterAndExpand"
        Text="{Binding name}"
        TextColor="{Binding color}" />
    
  • AndresQuiValAndresQuiVal Member ✭✭
    edited October 2019

    @JoeManke so if an example i create a propery in other class, an static property, and i want this property be binded to an entry text property as following:

    entry.SetBinding(Entry.TextProperty, "StaticClass.TextEntry");

    is it ok? beacuse i have tried and it doesnt work.

  • AdamMeaneyAdamMeaney USMember ✭✭✭✭✭

    Sorry, missed a word in the Binding.

    nameLabel.SetBinding(Label.TextProperty, nameof(model_class.name));

    This points to the name property appropriately. Sorry about the typo.

  • RichyRichy Member ✭✭
    edited January 24

    @JoeManke said:
    You can't bind to a static class. You must set the BindingContext somewhere in your view hierarchy to an instance of an object, and that is where the values are pulled from.

    How to bind the following in C#
    <Label Text="{Binding .}" />

  • JoeMankeJoeManke USMember ✭✭✭✭✭

    @Richy

    label.SetBinding(Label.TextProperty, ".");

  • Prajakta.ShindePrajakta.Shinde INUniversity ✭✭✭
    edited August 11

    Hi @AdamMeaney , I've dynamic buttons generation in the code behind. Whenever user clicks on button I want to highlight the selected button and other buttons will be not in focus. I'm looking for Button's IsFocusedProperty to set it in code behind.
    I was trying below code. Any help is appreciated.

    ```
    Button readingButton = new Button();
    readingButton.Text = "Reading" + " " + readingCount;
    readingButton.HorizontalOptions = LayoutOptions.EndAndExpand;
    readingButton.VerticalOptions = LayoutOptions.FillAndExpand;
    readingButton.BorderColor = Color.FromHex("AED6F1");
    readingButton.TextColor = Color.FromHex("007AC3");
    readingButton.CornerRadius = 10;
    readingButton.BorderWidth = 1;
    readingButton.Padding = 10;
    readingButton.BackgroundColor = Color.Transparent;

    readingButton.SetBinding(Button.IsFocusedProperty, new Binding() { Source = readingButton, Path = "" });
    ```

  • AdamMeaneyAdamMeaney USMember ✭✭✭✭✭

    I would say you want something more like a Radio Button for that.

    https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/radiobutton

    It allows only one to be selected at a time, and you can change some of the styling of it to get what you want visually out of it.

    In the coming days, they will even theoretically be a templated control you can more easily modify the entire appearance of, like so.

Sign In or Register to comment.