gpt4 book ai didi

c# - 监听 XAML 中的全局变量变化

转载 作者:太空宇宙 更新时间:2023-11-03 22:55:47 27 4
gpt4 key购买 nike

我有一个全局变量指示我的应用程序是否处于只读模式

public static class Global
{
public static event PropertyChangedEventHandler StaticPropertyChanged;
private static void OnStaticPropertyChanged(string propertyName)
{
StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyName));
}

private static bool _isReadOnly = false;
public static bool IsReadOnly
{
get { return _isReadOnly; }
set
{
_isReadOnly = value;
OnStaticPropertyChanged("IsReadOnly");
}
}
}

现在我想在我所有的 GUI 中收听它以关闭编辑。例如我有一个 DataGrid

<UserControl xmlns:models="clr-namespace:MyApp.Models" >
<DataGrid IsReadOnly="{Binding Path=(models:Global.IsReadOnly)}" />
</UserControl>

如何在我的 ViewModel 中监听全局变量而不是局部变量?目前我收到错误消息

The name Global does not exist in the namespace Models.

但确实如此!我已经尝试重新编译并重新启动 VS。

最佳答案

您可以使用单例实现而不是使用静态属性。比起你有一个实例并且可以实现 INotifyPropertyChanged:

public class Global : INotifyPropertyChanged
{
private Global() { }
public Global Instance { get; } = new Global();

private bool _isReadOnly;
public bool IsReadOnly
{
get => _isReadOnly;
set
{
if (_isReadOnly != value)
{
_isReadOnly = value;
PropertyChanged?.Invoke(this,
new PropertyChangedEventArgs(nameof(IsReadOnly)));
}
}
}

public event PropertyChangedEventHandler PropertyChanged;
}

然后你可以像这样使用它:

<DataGrid IsReadOnly="{Binding Source={x:Static local:Global.Instance}, Path=IsReadOnly}" />

正如 Clemens 在评论中提到的,自 .Net 4.5 以来,有一个静态 PropertyChanged 事件也适用于静态属性:

public static event PropertyChangedEventHandler StaticPropertyChanged;

关于c# - 监听 XAML 中的全局变量变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45423532/

27 4 0
文章推荐: node.js - Mongoose 中的错误处理
文章推荐: html - CSS强制内联输入字段
文章推荐: Node.js - 类型错误 : Object # has no method