[英]How can I bind property in a static class?
I am making a WPF program by .net5 .我正在通过 .net5 制作 WPF 程序。
Here is my code:这是我的代码:
public class ThemeBase:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string name)=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
SolidColorBrush _PrimaryBackground;
public SolidColorBrush PrimaryBackground
{
get => _PrimaryBackground;
set { _PrimaryBackground = value;OnPropertyChanged("PrimaryBackground"); }
}
Boolean _IsBlur;
public Boolean IsBlur
{
get => _IsBlur;
set {
//some logic
}
}
}
And here is a subclass that inherits from it.这是一个继承自它的子类。
public class NormalWhite:ThemeBase
{
public NormalWhite() {
PrimaryBackground = new SolidColorBrush(Colors.Red);
IsBlur=false;
}
}
Finally, I set a static variable in a class named Global.cs
:最后,我在名为Global.cs
的类中设置了一个静态变量:
public class Global
{
public static Themes.ThemeBase Theme=new NormalWhite();
}
Here is the code in XAML:这是 XAML 中的代码:
<Border Background="{Binding Source=x:Static local:Global.Theme,Path=PrimaryBackground}">
After the program ran, the Binding Failure reports this error:程序运行后,Binding Failure报这个错误:
Severity Count Data Context Binding Path Target Target Type Description File Line Project
Error 1 String PrimaryBackground Border.Background Brush PrimaryBackground property not found on object of type String. \MainPage.xaml 23 Sample
Why I can't bind it?为什么我绑定不了Thank you.谢谢你。
The Source expression must be Source={x:Static local:Global.Theme}
- with braces: Source 表达式必须是Source={x:Static local:Global.Theme}
- 带大括号:
<Border Background="{Binding Source={x:Static local:Global.Theme},
Path=PrimaryBackground}">
Since WPF 4.5 you can also bind directly to static properties.从 WPF 4.5 开始,您还可以直接绑定到静态属性。
Turn Theme
into a property将Theme
变成属性
public class Global
{
public static Themes.ThemeBase Theme { get; set; } = new NormalWhite();
}
and bind to it with a path expression in parentheses:并使用括号中的路径表达式绑定到它:
<Border Background="{Binding Path=(local:Global.Theme.PrimaryBackground)}">
In case you want to change the Theme
value at runtime, you must also implement a change notification, as eg shown here: https://stackoverflow.com/a/41823852/1136211如果您想在运行时更改Theme
值,您还必须实现更改通知,如下所示: https : //stackoverflow.com/a/41823852/1136211
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.