Xamarin Forms ListView模板内部如何绑定ViewModel属性
Xamarin Forms ListView ItemTemplate内绑定ViewModel属性解决方案
你当前的写法将Label的整个BindingContext设置为了Page对象,导致原本属于列表项Model的Count属性无法正常解析。你需要绑定的ViewModel属性属于Page的BindingContext,不需要修改控件的全局BindingContext,只需要给对应绑定单独指定数据源即可。
方案1:通过x:Reference引用页面指定绑定源
你已经给ContentPage设置了x:Name="Page",直接在需要绑定ViewModel属性的地方指定Source为页面,路径前加BindingContext.访问ViewModel的属性即可:
首先修正ContextActions里的命令绑定(当前写法会绑定失败,因为Model中不存在这两个命令):
<ViewCell.ContextActions> <MenuItem Text="Edit" Command="{Binding BindingContext.EditItemCommand, Source={x:Reference Page}}" CommandParameter="{Binding .}"/> <MenuItem Text="Delete" Command="{Binding BindingContext.DeleteItemCommand, Source={x:Reference Page}}" CommandParameter="{Binding .}"/> </ViewCell.ContextActions>
然后修正显示Count的Label绑定:
<Label Text="{Binding Count}" IsVisible="{Binding BindingContext.CompoundItems, Source={x:Reference Page}}" HorizontalOptions="StartAndExpand"/>
方案2:通过RelativeSource查找父级控件绑定源
如果不想依赖页面的x:Name,可以通过查找ListView父级的方式获取ViewModel上下文,耦合度更低:
命令绑定写法:
<MenuItem Text="Edit" Command="{Binding BindingContext.EditItemCommand, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}" CommandParameter="{Binding .}"/>
IsVisible属性写法:
<Label Text="{Binding Count}" IsVisible="{Binding BindingContext.CompoundItems, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}" HorizontalOptions="StartAndExpand"/>
注意事项
- ViewModel中的
CompoundItems、EditItemCommand、DeleteItemCommand需要声明为公共属性 - ViewModel需要实现
INotifyPropertyChanged接口,保证属性变更时UI能同步更新
内容的提问来源于stack exchange,提问作者quintendc
相关产品推荐
相关产品推荐

