在Xamarin Forms中,我定义了一个自定义数据模板,如下所示:
<DataTemplate x:Key="MyControlDataTemplate">
<ViewCell>
<controls:MyControl/>
</ViewCell>
</DataTemplate>
此片段属于ListView
中的MainPage.xaml
,其绑定上下文设置为MainPageViewModel.cs
在MyControl
内部,我想绑定MainPageViewModel
的财产。
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{set binding here to MainPageViewModel property}" />
</Label.GestureRecognizers>
MainPageViewModel
有这个命令属性:
public Command<MyItem> LabelTappedCommand { get; set; }
我的想法是创建一个单独的Command
对象,通过设置CommandParameter
属性在每个单元格之间共享,但我现在仍然坚持使用Command
属性。
这可能吗?
通过2个简单的步骤,这当然是可能的。
x:Name=MainPage
。Command="{Binding Path=BindingContext.MyProperty, Source={x:Reference MainPage}}"
一样在绑定中引用它这是假设您的主页的BindingContext
设置为您的MainPageViewModel
,但无论哪种方式,您都可以得到这个想法。
我认为唯一的解决方案是通过MyControl.cs公开Command绑定。之后,您可以使用引用某些父控件的解决方案作为绑定上下文(在@Knoop的回答中描述,您说您知道它是如何工作的,所以我不会详细介绍这个)。