簡體   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