【问题标题】:Adding x:DataType to page xaml leads to errors in ListView DataTemplate properties将 x:DataType 添加到页面 xaml 导致 ListView DataTemplate 属性出错
【发布时间】:2023-01-16 01:20:46
【问题描述】:

我已经从代码后面为依赖注入设置了 ViewModel。我想在 xaml 中保留 IntelliSense 建议的可能性。一切似乎都正常,但是一旦我添加了x:DataType="viewModels:HomeViewModel",我就收到了Number property not found 并且无法运行我的解决方案的错误。为什么会这样以及如何解决这个问题?

如果我删除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>

【问题讨论】:

    标签: c# .net xaml maui


    【解决方案1】:

    当你添加

    x:DataType="viewModels:HomeViewModel"
    

    对于页面,VS 假定这适用于整个页面。目前还不够“聪明”,无法识别页面中的模板化控件将具有不同的DataType

    有两种方法可以解决这个问题。第一,您可以完全删除DataType。它不是必需的,只是 VS 用来为 XAML 绑定提供 Intellisense 的助手

    或者,您可以将另一个 DataType 添加到您的模板化控件中,告诉 VS 这些控件正在使用什么类型。

    <DataTemplate x:DataType="viewModels:MyModelClass">
    

    您需要为代码使用正确的xmlns 和类名

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      相关资源
      最近更新 更多