UserControl绑定到自身
本文关键字:绑定 UserControl | 更新日期: 2023-09-27 18:18:06
我创建了一个大型UserControl
,出于测试目的,我设置了BindingContext = this
。现在我需要一个BindableProperty
,所以我不能再用这个技巧了,那么我怎么设置它反射自己呢?
问题是,我在XAML中使用UserControl,然后它说,为SelectedDate绑定的元素不存在,当我设置BindingContext = this
。
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为另一个Date
可以。使用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/