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

问题描述 投票:0回答:2

在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属性。

这可能吗?

c# xaml xamarin xamarin.forms viewmodel
2个回答
0
投票

通过2个简单的步骤,这当然是可能的。

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

这是假设您的主页的BindingContext设置为您的MainPageViewModel,但无论哪种方式,您都可以得到这个想法。


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.