C# 实现PropertyChangedEvent时,消息值不能为null

C# 实现PropertyChangedEvent时,消息值不能为null,c#,xamarin,xamarin.forms,C#,Xamarin,Xamarin.forms,我有一个C代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading; namespace City { public static class MS { public static event EventHandler<PropertyChangedEventArgs> StaticPropertyC

我有一个C代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
namespace City
{
    public static class MS 
    {

        public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;

        private static void NotifyStaticPropertyChanged(string propertyName)
        {
            if (StaticPropertyChanged != null)
                StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
        }

        private static int timerSeconds;
        public static int TimerSeconds
        {
            get { return timerSeconds; }
            set { timerSeconds = value; NotifyStaticPropertyChanged("TimerSeconds"); }
        }
    }
}
这个XAML

 <Frame xmlns="http://xamarin.com/schemas/2014/forms" 
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
  x:Class="City.Test">

 <Label x:Name="timer" Text="{Binding Source={x:Static local:MS.TimerSeconds}}" />
        </Grid>
当我编译时,它会给我一个编译错误,说:

错误:值不能为null。参数名称:CLR名称空间城市

有人知道是什么导致了这一切吗。当我划出标签行或更改为Text=ABC时,错误消失了

您没有定义本地名称空间。您应该添加名称空间:xmlns:local=clr名称空间:City。将代码更改为以下内容:

 <Frame xmlns="http://xamarin.com/schemas/2014/forms" 
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
  xmlns:local="clr-namespace:City"
  x:Class="City.Test">

 <Label x:Name="timer" Text="{Binding Source={x:Static local:MS.TimerSeconds}}" />
        </Grid>
有关详细信息,请阅读您没有定义本地名称空间。您应该添加名称空间:xmlns:local=clr名称空间:City。将代码更改为以下内容:

 <Frame xmlns="http://xamarin.com/schemas/2014/forms" 
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
  xmlns:local="clr-namespace:City"
  x:Class="City.Test">

 <Label x:Name="timer" Text="{Binding Source={x:Static local:MS.TimerSeconds}}" />
        </Grid>

有关更多信息,请阅读

一件小事-您应该像这样引发事件:var spc=StaticPropertyChanged;如果spc!=null spcnull,新属性ChangedEventArgsPropertyName;。这是为了避免代码中任何潜在的线程问题。这是一个好习惯,即使它不适用于这个特定的代码。你真的在编译或运行代码时遇到这个错误吗?或者你可以使用C 6中的新语法:StaticPropertyChanged?.Invokenull,new PropertyChangedEventArgspropertyName@Melina,你能在你的问题中添加你的本地名称空间的定义吗?我强烈建议你不要使用静态类来保存数据和绑定数据。情况可能会发生-在您的代码中,您使用null sender调用事件。事件如果它现在正在工作,则可能无法与将来的Xamarin.Forms版本一起工作。至少使用singleton模式-它允许您实现INotifyPropertyChanged接口;如果spc!=null spcnull,新属性ChangedEventArgsPropertyName;。这是为了避免代码中任何潜在的线程问题。这是一个好习惯,即使它不适用于这个特定的代码。你真的在编译或运行代码时遇到这个错误吗?或者你可以使用C 6中的新语法:StaticPropertyChanged?.Invokenull,new PropertyChangedEventArgspropertyName@Melina,你能在你的问题中添加你的本地名称空间的定义吗?我强烈建议你不要使用静态类来保存数据和绑定数据。情况可能会发生-在您的代码中,您使用null sender调用事件。事件如果它现在正在工作,则可能无法与将来的Xamarin.Forms版本一起工作。至少使用单例模式-它允许您实现INotifyPropertyChanged接口。