我开发了UWP应用程序。我有一个Client类,它通过套接字管理与另一个应用程序的连接。
在我的ViewModel类中,我有一个名为TextConnect的静态属性,该属性绑定到我的View中的文本框。
建立连接后,我想在文本框中显示“已连接”。因此,我的ViewModel类实现了INotifyPropertyChanged,并且我有一个名为StaticPropertyChanged的静态EventHandler,用于通知视图我的TextConnect属性已更改:
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
并且在我的Client类中,当建立连接时,我更改了此属性的值:
ViewModel.TextConnect = "Connected";
修改我的Client类中的TextConnect属性的方法在另一个线程中运行。
但是当我尝试更改属性的值时,出现错误,表明我的事件StaticPropertyChanged为null:
System.NullReferenceException : 'Object reference not set to an instance of an object.'
当我的属性绑定到我的文本框时,为什么StaticPropertyChanged为null?
建立连接后,我想在文本框中显示“已连接”。因此,我的ViewModel类实现了INotifyPropertyChanged,并且我有一个名为StaticPropertyChanged的静态EventHandler
如果您想将TextBox Text
属性与ViewModel
的TextConnect
属性绑定,则TextConnect应该是非静态的,因为我们需要在set方法中调用PropertyChanged
(不能在静态方法中运行) 。如果要静态访问PropertyChanged
,则可以为ViewModel设置静态TextConnect
属性。有关详细步骤,请参考以下代码。
Xaml
Current
ViewModel
<ToggleSwitch Header="This is header" IsOn="{Binding IsOpen}" />
用法
public class MainPageViewModel : INotifyPropertyChanged
{
public static MainPageViewModel Current;
public MainPageViewModel()
{
Current = this;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string name = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private bool _isOpen;
public bool IsOpen
{
get { return _isOpen; }
set { _isOpen = value; OnPropertyChanged(); }
}
}