[英]Is it possible to use "PropertyChanged" on a bool in .NET MAUI?
I have been trying to detect it when these variables change, but I don't know how to do that since bools aren't supported by the "PropertyChanged" function. I also tried using the communityToolKit, but I have no idea how to use that.当这些变量发生变化时,我一直试图检测它,但我不知道该怎么做,因为“PropertyChanged”function 不支持布尔值。我也尝试使用 communityToolKit,但我不知道如何使用那。 I want it to call the function "IconUpdater"
我希望它调用 function“IconUpdater”
public class Status : INotifyPropertyChanged
{
public static bool isWorking { get; set; } = Preferences.Get("IsWorking", true);
public static bool isPaused { get; set; } = Preferences.Get("IsPaused", false);
public static void IconUpdater()
{
// The function I want to call \\
}
public event PropertyChangedEventHandler PropertyChanged;
}
You can use PropertyChanged
event to notify the changes of IsEnabled
property in your viewmodel.您可以使用
PropertyChanged
事件通知视图模型中IsEnabled
属性的更改。 Here's the code snippet below for your reference:以下是供您参考的代码片段:
public class MainPageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool _isWorking;
public bool IsEnabled
{
get
{
return _isWorking;
}
set
{
if(_isWorking != value)
{
_isWorking = value;
var args = new PropertyChangedEventArgs(nameof(IsEnabled));
PropertyChanged?.Invoke(this, args);
}
}
}
}
I recommend using the Community Toolkit MVVM package:https://learn.microsoft.com/en-us/do.net/communitytoolkit/mvvm/我推荐使用社区工具包 MVVM package:https://learn.microsoft.com/en-us/do.net/communitytoolkit/mvvm/
You can then simply do the following to use the INotifyPropertyChanged interface:然后,您只需执行以下操作即可使用 INotifyPropertyChanged 接口:
using CommunityToolkit.Mvvm;
public class MyViewModel : ObservableObject
{
private bool _myBool;
public bool MyBool
{
get => _myBool;
set => SetProperty(ref _myBool, value);
}
}
You can also modify the code in such a way that you directly call any other method from within the setter:您还可以修改代码,以便直接从 setter 中调用任何其他方法:
private bool _myBool;
public bool MyBool
{
get => _myBool;
set
{
SetProperty(ref _myBool, value);
IconUpdater();
}
}
Please mind that your class is using static properties.请注意,您的 class 正在使用 static 属性。 You cannot use
INotifyPropertyChanged
for that.您不能为此使用
INotifyPropertyChanged
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.