[英]MAUI not finding property in VIew Model List
我有一个简单的视图 model,其中一个属性包含 model,另一个属性包含模型列表。
我能够毫无问题地绑定“测试”模型的属性,但我无法让 XAML 识别出“ListModel”包含一个具有其自身属性的列表。 我已经查看了几个示例,了解如何设置视图 model 并在将其绑定到视图之前正确初始化列表,虽然 XAML 理解“ListModel”是一个属性,但我无法让它识别它是一个列表,因此它不会编译,这样我至少可以看看它是否不是由于某种原因而失败的智能感知。
这是有问题的视图 model,列表名为“ListModel”
public class TestViewModel
{
public TestModel Test { get; } = new TestModel();
public List<TestListModel> ListModel { get; set; }
public TestViewModel()
{
Initialize();
}
public void Initialize()
{
ListModel = new List<TestListModel>();
ListModel.Add(new TestListModel
{
ListProp1 = "First",
ListProp2 = "Second",
ListProp3 = "Third"
});
}
}
这是被放入列表中的 Model。 似乎视图没有看到这些属性。
public class TestListModel
{
public string ListProp1 { get; set; }
public string ListProp2 { get; set; }
public string ListProp3 { get; set; }
}
这是我目前的 XAML。
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp1.MainPage"
xmlns:local="clr-namespace:ViewModels"
x:DataType="local:TestViewModel"
>
<ScrollView>
<VerticalStackLayout
Spacing="25"
Padding="30,0"
VerticalOptions="Center">
<!--This works-->
<Entry Text="{Binding Test.Property1}"/>
<Entry Text="{Binding Test.Property2}"/>
<Entry Text="{Binding Test.Property3}"/>
<!--This does not work-->
<ListView
ItemsSource="{Binding ListModel}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding ListProp1}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</VerticalStackLayout>
</ScrollView>
</ContentPage>
view
和viewmodel
通常通过 XAML 中定义的数据绑定连接。 视图的BindingContext
通常是viewmodel
的一个实例。所以我认为您忘记将这两个元素与BindingContext
连接起来。
视图背后的代码:
public partial class MainPage : ContentPage
{
TestViewModel tv = new TestViewModel();
public MainPage()
{
InitializeComponent();
BindingContext = tv;
}
}
Xaml 中的代码:
<ScrollView>
<VerticalStackLayout
Spacing="25"
Padding="30,0"
VerticalOptions="Center">
<!--This works-->
<Entry Text="{Binding Test.Property1}"/>
<Entry Text="{Binding Test.Property2}"/>
<Entry Text="{Binding Test.Property3}"/>
<!--This works too-->
<ListView
HasUnevenRows="True"
ItemsSource="{Binding ListModel}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<VerticalStackLayout>
<Label Text="{Binding ListProp1}"/>
<Label Text="{Binding ListProp2}"/>
<Label Text="{Binding ListProp3}"/>
</VerticalStackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</VerticalStackLayout>
</ScrollView>
结果:
参考链接。
对于任何绊倒此的人:评论中的杰森已经回答了这个问题。 修复只是从 XAML 顶部删除 x:DataType,尽管我没有从中删除“xmlns:local”。
我所拥有的是一个视图模型,其中包含多个模型,这在删除 x:DataType 时似乎扰乱了智能感知。 删除它最初会阻止应用程序编译,因为它找不到我在 XAML 中拥有的属性。 一旦我清理并重建了解决方案,它就可以顺利编译和工作。
通过使 ItemSource 绑定到具有私有支持字段的 List,我能够修复错误,同时保持已编译的绑定就位。 如果没有私有属性,编译器似乎无法正确解析列表。 在我添加 listModel 后它编译了。 所以问题似乎是 setter 丢失了。
private List<TestListModel> listModel;
public List<TestListModel> ListModel { get => listModel; set => listModel = value; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.