因此,我创建了一个 Singleton 用于跟踪在整个应用程序中全局使用的 ToolTip 启用程序,但是当我尝试将其绑定到 ToolTip 时,它最初会绑定该值,但是当我更改 ToolTip 启用程序值时,绑定不更新。
这是创建与工具提示的绑定的用户控件:
public partial class ViewTreeClass : UserControl {
private void addStuff() {
EnvironmentalVariables.Instance.ToolTipEnable = true;
Binding bind = new Binding() {
Source = EnvironmentalVariables.Instance.ToolTipEnable,
};
ToolTip x = new ToolTip();
x.Content = "This is text";
user.SetBinding(ToolTipService.IsEnabledProperty, bind);
user.ToolTip = x;
EnvironmentalVariables.Instance.ToolTipEnable = false;
// Executing the above statement changes the variable, but ToolTipService.IsEnabledProperty does not change to reflect EnvironmentalVariables.Instance.ToolTipEnable
}
}
这是实现 INotifyPropertyChanged 的 Singleton:
public class EnvironmentalVariables : INotifyPropertyChanged {
private static EnvironmentalVariables instance = new EnvironmentalVariables();
public static EnvironmentalVariables Instance {
get {
if(instance == null) {
instance = new EnvironmentalVariables();
}
return instance;
}
}
private EnvironmentalVariables() { }
private bool tooltipEnable;
public bool ToolTipEnable {
get {
return tooltipEnable;
}
set {
if(tooltipEnable != value) {
tooltipEnable = value;
this.RaiseNotifyPropertyChanged("ToolTipEnable");
}
}
}
private void RaiseNotifyPropertyChanged(string property) {
if(PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
当我更改'EnvironmentalVariables.Instance.ToolTipEnable = false;' 它将 Singleton 变量更改为“false”,但不会将 ToolTipService.EnabledProperty 更新为“false”,并且 PropertyChanged 始终为空。我是否错过了某个地方对 PropertyChanged 的订阅?
Singleton 和 UC 都在不同的命名空间/类文件中。