简体   繁体   English

依赖属性默认值不被覆盖

[英]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 : 在我的Xaml代码中,我有一个带有以下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. 当我按下按钮时,onMyCommandExecuted被调用。 and the value of obj is "DEFAULT" 且obj的值为“ 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? 是否可以/可能最好将默认值设置为一个变量,然后可以从MyAdvancedStateControl轻松更改该变量? Thank you 谢谢

Make the constructor of MyAdvancedStateControl static . 使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. 对OverrideMetadata的调用应仅在将自身提供为此方法的forType参数的类型的静态构造函数执行 ,或通过类似的实例化进行。 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 来自DependencyProperty.OverrideMetadata

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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