依赖项 属性 默认值未被覆盖

Dependency property default value not being overriden

我正在尝试覆盖依赖项的值 属性 但它似乎不起作用。

在我的 Xaml 代码中,我有一个带有以下命令参数的按钮:

CommandParameter="{Binding State,Mode=OneWay}

在这里我声明我的依赖关系属性:

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

然后在这里我尝试获取该值以在覆盖它之后使用它。 当我按下按钮时, onMyCommandExecuted 被调用。 obj 的值为 "DEFAULT"

public class MyAdvancedStateControl : INotifyPropertyChanged
{

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

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

我是不是做错了什么?如果是这样,覆盖依赖项 属性 的值的最佳方法是什么? 将默认值设置为变量是否可能/可能更好,然后我可以从 MyAdvancedStateControl 轻松更改? 谢谢

构造 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.

来自DependencyProperty.OverrideMetadata

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