这是我第一次使用C#,以及.net。我试图了解MVVM以及它如何与我想要构建的屏幕一起工作。
单击其他按钮后,我在更改时,我的按钮文本没有更新。调试器显示即使OnPropertyChanged函数被调用,PropertyChanged也始终为null。
我查看了一些文档并查看了其他人提出类似问题的帖子,但这些解决方案都没有对我有用。我也在寻找解释,以便我能理解我做错了什么。
代码:
MonthViewPage.xaml
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Mobile_Release_POC_4.MonthViewPage"
xmlns:local="clr-namespace:Mobile_Release_POC_4;assembly=Mobile_Release_POC_4"
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.Input"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<ContentPage.BindingContext>
<local:WeekViewDatesViewModel MiddleWeekViewDate='{x:Static sys:DateTime.Now}' />
</ContentPage.BindingContext>
<StackLayout>
<Label Text="Monday, April 27, 2015"
HorizontalOptions="Center"></Label>
<Grid Padding="0" ColumnSpacing="-2">
<Grid.RowDefinitions>
<RowDefinition Height="75" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions >
<ColumnDefinition Width="50" />
</Grid.ColumnDefinitions>
<Button x:Name="monthViewDateButton1"
Text="{Binding MiddleWeekViewDate}"
FontSize="10"
Grid.Row="0"
Grid.Column="0"
/>
<Button x:Name="monthViewDateButton2"
Text="Tue 4/28"
FontSize="10"
Grid.Row="0"
Grid.Column="1"
Clicked="OnButtonClicked"
/>
</Grid>
</StackLayout>
MonthViewPage.xaml.cs
using Xamarin.Forms;
namespace Mobile_Release_POC_4
{
public partial class MonthViewPage : ContentPage
{
public MonthViewPage ()
{
InitializeComponent();
}
void OnButtonClicked(object sender , EventArgs args){
WeekViewDatesViewModel dc = new WeekViewDatesViewModel ();
dc.MiddleWeekViewDate = new DateTime (2014, 2, 2);
}
}
WeekViewDatesViewModel.cs
namespace Mobile_Release_POC_4
{
public class WeekViewDatesViewModel : INotifyPropertyChanged
{
DateTime middleWeekViewDate;
public event PropertyChangedEventHandler PropertyChanged;
public DateTime MiddleWeekViewDate
{
set
{
if (middleWeekViewDate != value)
{
middleWeekViewDate = value;
OnPropertyChanged("MiddleWeekViewDate");
}
}
get
{
return middleWeekViewDate;
}
}
protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
}
谢谢
答案 0 :(得分:0)
只创建一个ViewModel,其范围是页面的生命周期(至少)。
将您的代码更改为:
public partial class MonthViewPage : ContentPage
{
public WeekViewDatesViewModel VM { get; set; }
public MonthViewPage ()
{
DataContext = VM = new WeekViewDatesViewModel();
InitializeComponent();
}
void OnButtonClicked(object sender , EventArgs args){
VM.MiddleWeekViewDate = new DateTime (2014, 2, 2);
}
}