依赖属性默认值不会被覆盖

编程入门 行业动态 更新时间:2024-10-22 02:42:33
本文介绍了依赖属性默认值不会被覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

依赖属性默认值不会被覆盖

本文发布于:2023-11-08 07:41:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568763.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:被覆   默认值   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!