Search code examples
c#wpfdata-bindingwpf-controlsdependency-properties

Dependency property default value not being overriden


I am trying to override the value of a dependency property but it doesn't seem to be working.

In my Xaml code I have a button with the following CommandParameter :

CommandParameter="{Binding State,Mode=OneWay}

and here I declare my dependency property:

public class MyStateControl : UserControl
{
  public MyStateControl()
  {
      this.InitializeComponent();
  }

  public string State
  {
    get { return (string)this.GetValue(StateProperty); }
    set { this.SetValue(StateProperty, value); } 
  }
  public static readonly DependencyProperty StateProperty = DependencyProperty.Register(
    "State", typeof(string), typeof(MyStateControl),new   PropertyMetadata("DEFAULT"));
}

and then here I try to get that value to use it, after overriding it. When I press the button, onMyCommandExecuted gets called. and the value of obj is "DEFAULT"

public class MyAdvancedStateControl : INotifyPropertyChanged
{

  public MyAdvancedStateControl()
  {
   MyStateControl.StateProperty.OverrideMetadata(typeof(MyAdvancedStateControl), new PropertyMetadata("Successfully overriden"));
  }

  private void onMyCommandExecuted(object obj)
  {
    //TODO
  }
}

Am I doing something wrong? If so, what's the best way to override the value of a dependency property? And would it be possible/ probably better to set the default value as a variable that I can then change easily from MyAdvancedStateControl? Thank you


Solution

  • Make the constructor of MyAdvancedStateControl static.

    Dependency property metadata should be overridden before the property system uses the dependency property. This equates to the time that specific instances are created using the class that registers the dependency property. Calls to OverrideMetadata should only be performed within the static constructors of the type that provides itself as the forType parameter of this method, or through similar instantiation. Attempting to change metadata after instances of the owner type exist will not raise exceptions, but will result in inconsistent behaviors in the property system.

    From DependencyProperty.OverrideMetadata

    public static MyAdvancedStateControl()
    {
        MyStateControl.StateProperty.OverrideMetadata(typeof(MyStateControl), new PropertyMetadata("Successfully overriden"));
    }