UserControl绑定到自身

时间:2016-11-16 12:59:12

标签: c# xamarin binding xamarin.forms

我创建了一个大UserControl,为了测试目的,我设置了BindingContext = this。现在我需要一个BindableProperty,所以我不能再使用这个技巧,所以如何设置它以反映自己呢?
问题是,我在XAML中使用UserControl,然后它说,当我设置BindingContext = this时,为SelectedDate绑定的元素不存在。

UserControl是如此复杂,我唯一可以在XAML中定义的是像

这样的主要内容。
<?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" />

我找不到正确的方法

我创建了一个简单的UserControl,所以你可以看到,我正在尝试做什么

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);
   }
}

可以从外部将SelectedDate设置为另一个日期。

1 个答案:

答案 0 :(得分:1)

是的,你可以。使用x:参考。

<Button Text="{Binding Date3,Source={x:Reference testControl}"
        FontSize="{Binding SelectedDate, Converter={StaticResource myConverter},
             ConverterParameter={Binding Date3,Source={x:Reference testControl}}}" />

以下链接可帮助您了解此概念。 https://developer.xamarin.com/guides/xamarin-forms/xaml/xaml-basics/data_binding_basics/