Search code examples
c#xamarinxamarin.formsdata-binding

Can I add to the functionality of Grid so I can specify new Grid().BindIsVisible( xx );


Here is an example:

var grid3Help = 
   new Grid().Bind(Grid.IsVisibleProperty, nameof(HelpIconVisible), source: this)

Is there some way that I could add to Grid to make it possible for me to change this to:

var grid3Help = new Grid().BindIsVisible(HelpIconVisible, source: this)

Note that if possible I would like to have an extension method but I am not sure how to handle the setting of "source: this"


Solution

  • If you are ok with creating and using a custom Grid (having the same properties as a Grid) instead:

    public class CustomGrid: Grid
    {
        public CustomGrid() : this() { }
    
        public void BindIsVisible(string bindobj, object sourceobj = null) {
              SetBinding(Grid.IsVisibleProperty, bindobj)
       }
    }
    
    var grid3Help = new CustomGrid().BindIsVisible(nameof(HelpIconVisible), source: this)
    

    With extension method:

    namespace ExtensionMethods
    {
        public static class MyExtensions
        {
            public static void BindIsVisible(this Grid grid, string boundproperty)
            {
                grid.SetBinding(VisualElement.IsVisibleProperty, boundproperty);
                return;
            }
        }
    }
    

    Don't forget to include the namespace: using ExtensionMethods;

    In both cases you will have to send the parameter with nameof() otherwise you can try something a bit complicated Finding the variable name passed to a function