问题描述
<ViewCell>
<ViewCell.View>
<Label Text="{Binding ABC}"></Label>
</ViewCell.View>
</ViewCell>
假设这个视单元在 ListView 内.如果内容页面与视图模型绑定,我如何获得对内容页面绑定的引用.目前,ABC"正在引用列表中某个对象的属性,但我想从内容页面的 bindingcontext 中获取该值.
Assuming this viewcell was inside ListView. If the content page was binding with a view model, how can I get a reference to the content page's binding. Currently, 'ABC' is referencing the property of an object in the list but i want to get the value from the content page's bindingcontext.
<ffimageloading:CachedImage.GestureRecognizers>
<TapGestureRecognizer BindingContext="{x:Reference page}" Command="{Binding OnSignInCommand}" CommandParameter="{Binding Model}" />
</ffimageloading:CachedImage.GestureRecognizers>
推荐答案
@qubuss 在下面给出了正确答案,但我想提供更多上下文并展示示例以使其更清楚:
@qubuss gave the correct answer below, but I would like to give more context and show an example to make it more clear:
让我们考虑以下页面:
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="firstPage" -->this reference parent context
x:Class="Your_Class_Name">
<ListView x:Name="ListSource"
ItemsSource="{Binding ListSource}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
// this come from item source
<Label Text="{Binding ABC}"></Label>
<Button Command="{Binding BindingContext.CommandFromParent
, Source={x:Reference firstPage} }" />
</Grid>
</ViewCell>
/DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
你的视图模型应该是这样的
your view Model should look like that
public class ViewModelName
{
private List<YourDataType> _listSource = new List<YourDataType>();
public List<YourDataType> ListSource
{
get => _listSource;
set
{
_listSource = value;
RaisePropertyChanged();
}
}
public ICommand CommandFromParent => new Command(HandleYourActionHere);
}
}
说明当我们编写BindingContext.CommandFromParent
时,BindingContext代表firstPage(x:Name=firstPage")
的BindingContext,其类型为ViewModelName
ExplanationWhen we write BindingContext.CommandFromParent
, BindingContext represents the BindingContext of firstPage(x:Name="firstPage")
which is of type ViewModelName
这篇关于Xamarin 表单:如何引用父绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!