Question

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 ?

Was it helpful?

Solution

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

OTHER TIPS

Easy.

Create an attached DependencyProperty on the DependencyObject Type.

public static readonly DependencyProperty DerpProperty = 
  DependencyProperty.RegisterAttached(
  "Derp",
  typeof(DependencyObject),
  typeof(Herp),
  new FrameworkPropertyMetadata());

public static void SetDerp(DependencyObject element, Herp value)
{
    element.SetValue(DerpProperty, value);
}

public static Herp GetDerp(DependencyObject element)
{
    return (Herp)element.GetValue(DerpProperty);
}

Defined on any type, it can be used on any type as well. In this example, it creates a new property called Derp on all DependencyObject instances that gets/sets an associated Herp value.

Assuming this is defined in a type called LolKThx in the namespace WpfFtw, you might use it in this way...

<Textblock 
    xmlns:lol="clr-namespace:WpfFtw" 
    lol:LolKThx.Derp="There's an implicit conversion for string -> Herp, btw" />

You can specify callbacks in your FrameworkPropertyMetadata to perform any action you need on setting/getting values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top