[英]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.