【问题标题】:How can I bind property in a static class?如何在静态类中绑定属性?
【发布时间】:2021-03-05 04:40:05
【问题描述】:

我正在通过 .net5 制作 WPF 程序。

这是我的代码:

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
            }
        }
}

这是一个继承自它的子类。

public class NormalWhite:ThemeBase
    {
        public NormalWhite() {
            PrimaryBackground = new SolidColorBrush(Colors.Red);
            IsBlur=false;
        }
    }

最后,我在一个名为Global.cs的类中设置了一个静态变量:

public class Global
{
   public static Themes.ThemeBase Theme=new NormalWhite();
}

这是 XAML 中的代码:

<Border Background="{Binding Source=x:Static local:Global.Theme,Path=PrimaryBackground}">

程序运行后,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

为什么我不能绑定它?谢谢。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    源表达式必须是Source={x:Static local:Global.Theme} - 带大括号:

    <Border Background="{Binding Source={x:Static local:Global.Theme},
                                 Path=PrimaryBackground}">
    

    从 WPF 4.5 开始,您还可以直接绑定到静态属性。

    Theme 转为属性

    public class Global
    {
        public static Themes.ThemeBase Theme { get; set; } = new NormalWhite();
    }
    

    并用括号中的路径表达式绑定到它:

    <Border Background="{Binding Path=(local:Global.Theme.PrimaryBackground)}">
    

    如果您想在运行时更改 Theme 值,您还必须实现更改通知,例如此处显示:https://stackoverflow.com/a/41823852/1136211

    【讨论】:

    • 恐怕VS报这个错误:XamlParseException:Type reference cannot find type named“{clr-namespace:Sample;assembly=Sample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null}全球主题”。在我把主题变成财产之后。
    • 但是,{Binding Source={x:Static local:Global.Theme}, Path=PrimaryBackground} 方式运行良好。
    • 我不知道您到底出了什么问题,但是当您使用 WPF 4.5 或更高版本时,静态属性 Path 当然可以工作。如果您更改主题,您将需要它。不要忘记在路径表达式周围加上括号。
    猜你喜欢
    • 2014-09-10
    • 2021-08-26
    • 2014-01-29
    • 2012-10-15
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    相关资源
    最近更新 更多