Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Scope Attached Dependency Property

I would like to do something like a static variable in normal programming, only in XAML using Dependency Properties.

Meaning I would like the property to :

  • Be one instance
  • Be visible by every element
  • Be bindable

How do I do that ?

like image 284
michal.ciurus Avatar asked Dec 13 '13 14:12

michal.ciurus


1 Answers

It sounds like you want an attached property that always applies to every element. I think the easiest way to make that work would be through the CoerceValueCallback of the dependency property, where you could force it to always return the static value regardless of the element's local value (you would update the static value in the PropertyChangedCallback).

This seems like an odd way to use the dependency property system, though. Maybe you just need a central binding source? You can bind to a static instance by assigning Binding.Source using x:Static:

{Binding Source={x:Static Member=global:GlobalObject.SharedInstance},
         Path=SharedValue}

Note that SharedValue isn't a static property; it's a property of an instance accessed from the static SharedInstance property:

public class GlobalObject {
    private static readonly GlobalObject _instance = new GlobalObject();

    public static GlobalObject SharedInstance { get { return _instance; } }

    public object SharedValue { get; set; }
}
like image 197
nmclean Avatar answered Sep 28 '22 15:09

nmclean