依赖属性默认值不会被覆盖 [英] Dependency property default value not being overriden

查看:83
本文介绍了依赖属性默认值不会被覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在我的Xaml代码中,我有一个带有以下内容的按钮CommandParameter:

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

,然后在这里我尝试覆盖该值后使用该值。
当我按下按钮时,onMy CommandExecuted被调用。并且obj的值为 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
  }
}

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

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

推荐答案

使 MyAdvancedStateControl的构造函数 静态


依赖属性元数据应在属性
系统之前被覆盖使用依赖项属性。这等于使用注册
依赖项属性的类创建
个特定实例的时间。 对OverrideMetadata的调用仅应在提供
本身作为此方法的forType参数的类型的静态构造函数中执行
,或通过类似的
实例化。在
所有者类型的实例存在之后尝试更改元数据不会引发异常,但会导致
财产系统中的行为不一致。

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

这篇关于依赖属性默认值不会被覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆