簡體   English   中英

如何在靜態類中綁定屬性?

[英]How can I bind property in a static class?

我正在通過 .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

為什么我綁定不了謝謝你。

Source 表達式必須是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM