我有一个具有ItemsSource
可绑定属性和名为DataTemplate
的{{1}}可绑定属性的自定义控件,如下所示:
ItemTemplate
在public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create(
nameof(ItemsSource), typeof(IList), typeof(MyControl), propertyChanged: onItemsSourcePropertyChanged);
public static readonly BindableProperty ItemTemplateProperty = BindableProperty.Create(
nameof(ItemTemplate), typeof(DataTemplate), typeof(MyControl));
中的某个时刻,我正在遍历新项目并为每个项目实例化onItemsSourcePropertyChanged
,还将结果视图设置为项目的ItemTemplate
:
BindingContext
每一项都是 var view = (View)ItemTemplate.CreateContent();
view.BindingContext = item;
类,它实现MyViewObject
并在所有属性上引发INotifyPropertyChanged
。尽管PropertyChanged
是控件中的ItemsSource
,但我正在发送IList
。
该控件做了很多工作来弄清楚放置项目视图的位置,但是长话短说,它包含一个带有动态ObservableCollection<MyViewObject>
/ RowDefinitions
的网格,用于放置这些视图。 / p>
在XAML中,我声明了该控件并将其提供给以下ColumnDefinitions
:
DataTemplate
主要问题是 <controls:MyControl ItemsSource="{Binding ObservableCollectionOnViewModel}">
<controls:MyControl.ItemTemplate>
<DataTemplate x:DataType="viewObjects:MyViewObject">
<StackLayout Orientation="Horizontal"
HeightRequest="100"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<BoxView IsVisible="{Binding IsSelected}"
WidthRequest="4"
VerticalOptions="FillAndExpand"/>
<Label Text="Foo"
WidthRequest="128"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"/>
</StackLayout>
</DataTemplate>
</controls:MyControl.ItemTemplate>
</controls:MyControl>
上的IsVisible
绑定,无论我将ViewObject的BoxView
(IsSelected
)属性设置为(是,正在调用bool
,也尝试了PropertyChanged
,但无济于事。
我在XF源代码中闲逛了一段时间,发现Device.BeginInvokeOnMainThread
将其绑定存储在BindableObject
私有字段中。我在设置BindingContext之前和之后在其中找到了_properties
BindingProperty并检查了其状态。在这两种情况下,绑定上的IsVisible
属性都是null。 Source
字段似乎设置为_targetProperty
。
我像这样手动重新定义绑定(这不是一个选择,因为我将DataTemplate紧密耦合到使用者控件):
"IsSelected"
在重新定义绑定之后,我再次检查了 var view = (View)ItemTemplate.CreateContent();
var billy = (view as StackLayout).Children.First() as BoxView;
view.BindingContext = item;
billy.SetBinding(IsVisibleProperty, new Binding("IsSelected", source: item));
,它似乎可以正常工作(设置了字段,并且也达到了我想要的行为)。
我现在的假设是XAML中定义的初始绑定不起作用,因为创建billy._properties.First(p => p.Property == "IsVisible").Binding
时未设置BindingContext
。或与此事实相关的类似事物。
我的问题:有没有一种方法可以在XAML中定义绑定,还可以使用CreateContent()
动态实例化DataTemplate?
将CreateContent()
绑定到BoxView.BindingContext
似乎也可以解决此问题。