简体   繁体   中英

NET 4.5 XAML binding to static properties with updates, working but is there a better way?

Im sorry if it's a duplicate but I couldn't find the question similiar to this one.

From the stackoverflow other questions (this site is superb) I discovered how to bind XAML items to static class with event updates. It works that way:

XAML:

 <Label x:Name="label_cc_CPUPOWER" Content="{Binding Path=(database:Database.CPU_CPUPOWER)}"...

Code:

    public static class Database
{

    #region Event firing
    public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
    private static void NotifyStaticPropertyChanged(string propertyName)
    {
        if (StaticPropertyChanged != null)
            StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
    }
    #endregion


    //CPU
    private static string _CPU_CPUCLOCK;
    public static string CPU_CPUCLOCK
    {
        get { return _CPU_CPUCLOCK; }
        set
        {
            if (value != _CPU_CPUCLOCK)
            {
                _CPU_CPUCLOCK = value;

                NotifyStaticPropertyChanged("CPU_CPUCLOCK");
            }
        }
    }

    private static string _CPU_CPUPOWER;
    public static string CPU_CPUPOWER
    {
        get { return _CPU_CPUPOWER; }
        set
        {
            if (value != _CPU_CPUPOWER)
            {
                _CPU_CPUPOWER = value;

                NotifyStaticPropertyChanged("CPU_CPUPOWER");
            }
        }
    }

It works and Im really grateful to You that I don't have to figure this out all by myself BUT I have about 25-50 values to store like that. I Wonder if there's a way automate this instead of copy/paste with changing names in brackets?

I also thought about making an List for each object like CPU,RAM and just send EventChanged to the whole object but Im trying to minimize cpu usage and IMHO raising PropertyChanged to all objects while I just want to update two of five isn't good way to do that as whole object values would be refreshed.

Regards

Yes there are, check this out: PropertyChanged.Fody

Then all you have to do is to add :

using PropertyChanged;
...
[ImplementPropertyChanged]
public class MyClass
{
  public object Object {get;set;} 
// INotifyPropertyChanged implemented automatically @ compile-time
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM