我已经从代码后面设置了 ViewModel 以进行依赖注入。我想在 xaml 中留下 IntelliSense 建议的可能性。一切似乎都有效,但是一旦添加x:DataType="viewModels:HomeViewModel",我就会收到属性未找到的错误Number,并且无法运行我的解决方案。为什么会这样以及如何解决这个问题?
如果我删除x:DataType="viewModels:HomeViewModel",一切正常。
主页.xaml:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyApp.Pages.HomePage"
xmlns:viewModels="clr-namespace:MyApp.ViewModels"
x:DataType="viewModels:HomeViewModel"
Title=""
NavigationPage.HasNavigationBar="False">
<Frame>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0"></Label>
<ListView ItemsSource="{Binding TotalData}" Grid.Row="1">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="5">
<Label Text="{Binding Number}" Margin="0,0,10,0"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Frame>
</ContentPage>
Run Code Online (Sandbox Code Playgroud)
编辑:
根据杰森的回答,我HomePage.xaml应该是:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyApp.Pages.HomePage"
xmlns:viewModels="clr-namespace:MyApp.ViewModels"
xmlns:models="clr-namespace:MyApp.Models"
x:DataType="viewModels:HomeViewModel"
Title=""
NavigationPage.HasNavigationBar="False">
<Frame>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0"></Label>
<ListView ItemsSource="{Binding TotalData}" Grid.Row="1">
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:DataModel">
<ViewCell>
<Grid Padding="5">
<Label Text="{Binding Number}" Margin="0,0,10,0"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Frame>
</ContentPage>
Run Code Online (Sandbox Code Playgroud)
当你添加
x:DataType="viewModels:HomeViewModel"
Run Code Online (Sandbox Code Playgroud)
对于页面,VS 假设这适用于整个页面。目前它还不够“智能”,无法识别页面中存在一个具有不同内容的模板化控件。DataType
有两种方法可以解决这个问题。一,你可以DataType完全删除。它不是必需的,只是 VS 用于为 XAML 绑定提供 Intellisense 的帮助器
或者,您可以DataType向模板化控件添加另一个,告诉 VS 这些控件使用什么类型。
<DataTemplate x:DataType="viewModels:MyModelClass">
Run Code Online (Sandbox Code Playgroud)
您需要xmlns为代码使用正确的类名