【发布时间】:2021-03-05 03:02:25
【问题描述】:
我正在将项目从标准 Xamarin.Forms 移动应用程序转换为使用 MVVM 格式。在转换为 MVVM 之前,该应用程序的所有功能都按预期工作。为我的一个视图设置我的 ViewModel 并将SelectedDate 属性添加到我的DatePicker 后,我开始收到错误:The property 'SelectedDate' was not found in type 'DatePicker'.
启动 clean all 并重新构建后,我也开始收到另一个错误:No property, BindableProperty, or event found for "SelectedDate", or mismatching type between value and property.
我的 XAML 文件的适用部分:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
x:Class="StarTracker.AddAdventurePage"
BackgroundColor="{StaticResource lightBlue}">
<StackLayout HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand">
<CollectionView x:Name="NewAdventure"
HorizontalOptions="CenterAndExpand"
SelectionMode="None">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Text="Date Played: "
FontFamily="Axion"
TextColor="{StaticResource red}"
Grid.Row="0"
Grid.Column="0"/>
<DatePicker x:Name="PlayedDatePicker"
FontFamily="Axion"
Grid.Row="0"
Grid.Column="1"
SelectedDate="{Binding Date}"
TextColor="{StaticResource darkBlue}"
MinimumDate="08/17/2017"
MaximumDate="{x:Static sys:DateTime.Today}">
<DatePicker.Format>MM/dd/yyyy</DatePicker.Format>
</DatePicker>
视图模型:
private DateTime date;
public DateTime Date
{
get { return date; }
set
{
date = value;
OnPropertyChanged("Date");
}
}
在找到How to binding property in a behavior? 之后,我将我的ViewModel 更改为除了INotifyPropertyChanged 之外还派生自BindableObject,然后将Date getter/setter 更改为:
public static readonly BindableProperty DateProperty = BindableProperty.Create(
nameof(Date),
typeof(DateTime),
typeof(DatePicker));
public DateTime Date
{
get { return (DateTime)GetValue(DateProperty); }
set
{
SetValue(DateProperty, value);
OnPropertyChanged("Date");
}
}
我仍然有 IntelliSense 告诉我 SelectedDate 不是 DatePicker 中的属性,根据 https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.datepicker?redirectedfrom=MSDN&view=netframework-4.8#properties 是不准确的。我的其他Pickers 中的SelectedItem 绑定可以正常工作。
我缺少什么可以让我在DatePicker 中使用SelectedDate 属性并通过我的DataBindings 保存信息?
【问题讨论】:
标签: c# xamarin.forms mvvm data-binding datepicker