英文:
.NET MAUI binding two DataType on single XAML tag
问题
我有以下的XAML代码:
<ContentPage x:DataType="viewmodel:MonkeyViewModel">
<CollectionView ItemsSource="{Binding MonkeyList}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="model:Monkey">
<Label Text="{Binding Id}" />
<Label Text="{Binding Name}" />
<Label Text="Edit">
<Label.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding EditCommand}"
CommandParameter="{Binding Id}"/>
</Label.GestureRecognizers>
</Label>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</ContentPage>
MonkeyList 和 EditCommand 来自于 viewmodel:MonkeyViewModel。
Id 和 Name 来自于 model:Monkey。
在标签 <TapGestureRecognizer> 中,{Binding EditCommand} 由于在 Monkey 的数据上下文中找不到 EditCommand 而无法工作。
如何使 EditCommand 绑定到 MonkeyViewModel,而 Id 绑定到 Monkey?我期望 <Label> 的工作方式类似于 HTML 的 <A> 链接:<a href="javascript:edit(id)">Edit</a> 或:<a onclick="edit(id)">Edit</a>。
英文:
I have the following XAML code:
<ContentPage x:DataType="viewmodel:MonkeyViewModel">
<CollectionView ItemsSource="{Binding MonkeyList}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="model:Monkey">
<Label Text="{Binding Id}" />
<Label Text="{Binding Name}" />
<Label Text="Edit">
<Label.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding EditCommand}"
CommandParameter="{Binding Id}"/>
</Label.GestureRecognizers>
</Label>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</ContentPage>
The MonkeyList and EditCommand come from viewmodel:MonkeyViewModel.
The Id and Name come from model:Monkey.
On the tag <TapGestureRecognizer> , the {Binding EditCommand} doesn't work due to the EditCommand not being found in the data context of Monkey.
How can I make the EditCommand binding on MonkeyViewModel and Id binding on Monkey?
I would expect the <Label> works like a html <A> link: <a href="javascript:edit(id)">Edit</a> or: <a onclick="edit(id)">Edit</a>
答案1
得分: 1
Change the Command binding to use a Relative Binding as follows:
<TapGestureRecognizer
Command="{Binding EditCommand, Source={RelativeSource AncestorType={x:Type viewmodel:MonkeyViewModel}}}"
CommandParameter="{Binding Id}"/>
英文:
Just change the Command binding to use a Relative Binding as follows:
<TapGestureRecognizer
Command="{Binding EditCommand, Source={RelativeSource AncestorType={x:Type viewmodel:MonkeyViewModel}}}"
CommandParameter="{Binding Id}"/>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论