[英]Xamarin.Forms Binding to Custom Control Not Working When Binding Is Set In Parent
[英]How can I set custom control binding to parent view model property in Xamarin Forms when using a ListView?
在Xamarin Forms中,我定义了一个自定义数据模板,如下所示:
<DataTemplate x:Key="MyControlDataTemplate">
<ViewCell>
<controls:MyControl/>
</ViewCell>
</DataTemplate>
此代码段属于MainPage.xaml
中的ListView
,其绑定上下文设置为MainPageViewModel.cs
在MyControl
内部,我想绑定到MainPageViewModel
的属性。
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{set binding here to MainPageViewModel property}" />
</Label.GestureRecognizers>
MainPageViewModel
具有以下命令属性:
public Command<MyItem> LabelTappedCommand { get; set; }
这个想法是通过设置CommandParameter
属性来创建一个在每个单元之间共享的单个Command
对象,但是我现在仍然停留在Command
属性上。
这可能吗?
只需两个简单的步骤就可以实现。
x:Name=MainPage
。 Command="{Binding Path=BindingContext.MyProperty, Source={x:Reference MainPage}}"
这是基于将主页的BindingContext
设置为MainPageViewModel
的假设,但是您可以通过两种方式来实现。
我认为唯一的解决方案是通过MyControl.cs公开Command绑定。 之后,您可以使用引用某些父控件作为绑定上下文的解决方案(在@Knoop的回答中进行了描述,并且您说您知道它是如何工作的,因此在此不做详细介绍)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.