Lit*_*nny 6 xaml binding xamarin binding-context
<ViewCell>
<ViewCell.View>
<Label Text="{Binding ABC}"></Label>
</ViewCell.View>
</ViewCell>
Run Code Online (Sandbox Code Playgroud)
假设此视单元位于ListView中。如果内容页面与视图模型绑定,那么如何获得对内容页面绑定的引用。当前,“ ABC”正在引用列表中对象的属性,但我想从内容页面的绑定上下文中获取值。
<ffimageloading:CachedImage.GestureRecognizers>
<TapGestureRecognizer BindingContext="{x:Reference page}" Command="{Binding OnSignInCommand}" CommandParameter="{Binding Model}" />
</ffimageloading:CachedImage.GestureRecognizers>
Run Code Online (Sandbox Code Playgroud)
jfm*_*fmg 13
您可以使用RelativeSource.
改变这一行
<Label Text="{Binding ABC}"></Label>
Run Code Online (Sandbox Code Playgroud)
对此
<Label Text="{Binding ABC, Source={RelativeSource AncestorType={x:Type viewModel:YourViewModelName}}}"></Label>
Run Code Online (Sandbox Code Playgroud)
不要忘记viewModel在文件顶部添加 xml 命名空间:
xmlns:viewModel="clr-namespace:YourProject.ViewModels"
Run Code Online (Sandbox Code Playgroud)
您可以RelativeSource在此处阅读有关绑定的所有信息:https :
//docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/relative-bindings#bind-to-an-ancestor
Min*_*wzy 10
甚至qubus都给出了正确的答案,我想用示例来回答这个问题,以使其更清楚
考虑一下我们有一个页面
<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>
Run Code Online (Sandbox Code Playgroud)
您的视图模型应如下所示
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);
}
}
Run Code Online (Sandbox Code Playgroud)
发生什么情况的小解释,当我们写BindingContext.CommandFromParentBindingContext时表示firstPage(x:Name =“ firstPage”)的BindingContext,它是ViewModelName
小智 5
您需要添加BindingContext="{x:Reference viewmodel}内部标签。
<ViewCell>
<ViewCell.View>
<Label Text="{Binding ABC}" BindingContext="{x:Reference Name_Of_Parent}"></Label>
</ViewCell.View>
</ViewCell>
Run Code Online (Sandbox Code Playgroud)
在 Name_Of_Parent 中,您输入组件的名称。如果您使用 MVVM 和 ViewModel 类,则必须添加x:Name到绑定上下文中:
<ContentPage.BindingContext>
<mvvm:MasterPageModel
x:Name="viewmodel"/>
</ContentPage.BindingContext>
Run Code Online (Sandbox Code Playgroud)
这是描述它的文档。
| 归档时间: |
|
| 查看次数: |
8633 次 |
| 最近记录: |