繁体   English   中英

使用ListView时,如何在Xamarin Forms中将自定义控件绑定设置为父视图模型属性?

[英]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属性上。

这可能吗?

只需两个简单的步骤就可以实现。

  1. 给您的xaml页面一个x:Name=MainPage
  2. 在像这样的绑定中引用它Command="{Binding Path=BindingContext.MyProperty, Source={x:Reference MainPage}}"

这是基于将主页的BindingContext设置为MainPageViewModel的假设,但是您可以通过两种方式来实现。

我认为唯一的解决方案是通过MyControl.cs公开Command绑定。 之后,您可以使用引用某些父控件作为绑定上下文的解决方案(在@Knoop的回答中进行了描述,并且您说您知道它是如何工作的,因此在此不做详细介绍)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM