【发布时间】:2023-01-24 16:49:33
【问题描述】:
我有一个简单的视图模型,其中一个属性包含一个模型,另一个属性包含一个模型列表。
我能够毫无问题地绑定“测试”模型的属性,但我无法让 XAML 识别“ListModel”包含一个具有其自身属性的列表。我已经查看了几个示例,了解如何设置视图模型并在将列表绑定到视图之前正确初始化列表,虽然 XAML 理解“ListModel”是一个属性,但我无法让它识别它是一个列表,因此它不会编译,这样我至少可以看看它是否不是由于任何原因而失败的智能感知。
这是有问题的视图模型,列表名为“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"
});
}
}
这是被放入列表中的模型。似乎视图没有看到这些属性。
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>
【问题讨论】:
-
摆脱
x:DataType -
我删除了 XAML 的那部分,所有其他绑定都损坏了。
-
“坏了”不是对问题的有用描述。您是否收到编译器错误、运行时异常、崩溃等?
DataType是一个帮助器,它允许 VS 为你的 XAML 绑定提供 Intellisense。这不应该是编译/运行时的问题,只是设计时的问题。我从不在我的 XAML 中使用它。