UserControl binding to itself

LasseMadsenLasseMadsen USMember ✭✭
edited November 2016 in Xamarin.Forms

I have created a large UserControl, and for the testing purpose, I had set the BindingContext = this. Now I need a BindableProperty, so I can not use this trick anymore, so how can I set it to reflect itself?

The problem is, that I am using the UserControl in XAML, and then it say, the element binded for SelectedDate does not exist, when I set BindingContext = this

The UserControl is so complex, that the only thing, I can define in XAML is the main like

<?xml version="1.0" encoding="UTF-8"?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="ComplexUserControl" />

Which I do not find the right way to go

I have created a simple UserControl, so you can see, what I am trying to do

class Test : Grid
{
   public static readonly BindableProperty SelectedDateProperty = BindableProperty.Create("SelectedDate", typeof(DateTime), typeof(Test), defaultValue: DateTime.Now, defaultBindingMode: BindingMode.TwoWay);

   public DateTime Date1
   {
      get { return DateTime.Today.AddDays(-1); }
   }

   public DateTime Date2
   {
      get { return DateTime.Today; }
   }

   public DateTime Date3
   {
      get { return DateTime.Today.AddDays(1); }
   }

   public Test()
   {
      InitializeComponent();
   }

   private void InitializeComponent()
   {
      ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
      ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
      ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

      Button btn1 = new Button();
      btn1.SetBinding(Button.FontSizeProperty, new Binding("SelectedDate", converter: new IsSelectedFontSizeConverter(), converterParameter: Date1));
      btn1.SetBinding(Button.TextProperty, new Binding("Date1", stringFormat: "dd"));
      Children.Add(btn1, 0, 0);

      Button btn2 = new Button();
      btn2.SetBinding(Button.FontSizeProperty, new Binding("SelectedDate", converter: new IsSelectedFontSizeConverter(), converterParameter: Date2));
      btn2.SetBinding(Button.TextProperty, new Binding("Date2", stringFormat: "dd"));
      Children.Add(btn2, 1, 0);

      Button btn3 = new Button();
      btn3.SetBinding(Button.FontSizeProperty, new Binding("SelectedDate", converter: new IsSelectedFontSizeConverter(), converterParameter: Date3));
      btn3.SetBinding(Button.TextProperty, new Binding("Date3", stringFormat: "dd"));
      Children.Add(btn3, 2, 0);
   }
}

It shall be possible from the outside to set the SelectedDate to another Date.

Sign In or Register to comment.