我想在我的视图中显示一个BleDevice类型的列表(可观察的集合)。我在.net maui(.net 7)中使用mvvm模式。
产品型号:
public class BleDevice
{
public BleDevice(){}
public BleDevice(string name, string mac)
{
Name = name;
MacAddress = mac;
}
public string Name { get; set; }
public string MacAddress { get; set; }
}
视图模型:
public partial class MainViewModel: ObservableObject
{
public MainViewModel()
{
devices = new ObservableCollection<BleDevice>();
devices.Add(new BleDevice("Mystronics Winder", "00:00:00:00:00"));
devices.Add(new BleDevice("Living Room TV", "25:e7:aa:05:84"));
}
[ObservableProperty]
ObservableCollection<BleDevice> devices;
}
视图(xaml):(已编辑)
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp2.MainPage"
xmlns:viewmodel="clr-namespace:MauiApp2.ViewModel"
xmlns:model="clr-namespace:MauiApp2.Model"
x:DataType="viewmodel:MainViewModel">
<VerticalStackLayout>
<CollectionView ItemsSource="{Binding Devices}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="{model:BleDevice}">
<Grid>
<Label Text="{Binding Name}"/>
<Label Text="{Binding MacAddress}"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</VerticalStackLayout>
</ContentPage>
错误:XFC0045 Binding: Property "Name" not found on "MauiApp2.ViewModel.MainViewModel". MauiApp2 \source\repos\MauiApp2\MauiApp2\View\MainPage.xaml
为什么它能识别"{Binding Devices}"
,但不能识别"{Binding Name}"
和"{Binding MacAddress}"
?
1条答案
按热度按时间pn9klfpd1#
ViewModel删除
[ObservableProperty]
属性并更改为:**查看(xaml)**删除
x:DataType="xxx"
: