Xamarin MVVM数据绑定后ListView文本内容未在UI渲染问题
问题根源
你遇到的是Xamarin.Forms编译绑定的类型匹配问题:
你在ContentPage节点全局声明了x:DataType="viewmodels:ExampleListViewModel",所有子节点默认会用这个类型校验绑定属性。而ListView.ItemTemplate的绑定上下文是ExampleList集合中的单个example实体对象,和页面全局的DataType类型不匹配,就出现了两种异常情况:
- 直接绑
{Binding ID}:编译校验时在ExampleListViewModel中找不到ID属性,抛出XFC0045错误 - 绑
{Binding Example.Desc}:编译能过是因为ExampleListViewModel确实有Example属性,但运行时列表项的上下文是example实体,不存在Example属性,所以文本不显示 - 热重载临时生效:是因为运行时修改XAML时编译绑定临时失效,切换为运行时绑定,能正确匹配到
example实体的属性,所以能显示,重新编译后又会触发编译绑定校验。
解决步骤
1. 修改XAML代码
首先在ContentPage的命名空间声明中增加实体类的命名空间引用,然后给DataTemplate单独指定正确的x:DataType:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="App2.Views.ExampleListPage" xmlns:viewmodels="clr-namespace:App2.ViewModels" <!-- 新增models命名空间引用 --> xmlns:models="clr-namespace:App2.Models" x:DataType="viewmodels:ExampleListViewModel" Title="Example List"> <ContentPage.BindingContext> <viewmodels:ExampleListViewModel/> </ContentPage.BindingContext> <ListView x:Name="listView" Margin="20" SelectedItem="{Binding SelectedElement, Mode=TwoWay}" ItemsSource="{Binding ExampleList}" RefreshCommand="{Binding RefreshCommand}" IsRefreshing="{Binding IsBusy, Mode=OneWay}" IsPullToRefreshEnabled="True"> <ListView.ItemTemplate> <!-- 给DataTemplate单独指定DataType为example实体类型 --> <DataTemplate x:DataType="models:example"> <!-- 直接绑定example实体的属性即可 --> <TextCell Text="{Binding ID}" Detail="{Binding Desc}"/> </DataTemplate> </ListView.ItemTemplate> </ListView> </ContentPage>
2. 可选优化(建议修改)
你的example实体类目前只声明了PropertyChanged事件,没有完整实现INotifyPropertyChanged接口,如果后续需要修改实体属性后UI自动更新,需要补充实现:
public class example : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; // 字段变更时触发事件的方法 protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } // 其余属性保持不变 }
内容的提问来源于stack exchange,提问作者ABpositive
相关产品推荐
相关产品推荐

