C# WPF:更改DependencyProperty时运行代码
在一个简单的用户控件中,我希望能够在依赖项属性更改时随时运行代码C# WPF:更改DependencyProperty时运行代码,c#,wpf,wpf-controls,dependency-properties,C#,Wpf,Wpf Controls,Dependency Properties,在一个简单的用户控件中,我希望能够在依赖项属性更改时随时运行代码 public static readonly DependencyProperty Text1Property = DependencyProperty.Register("Text1", typeof(string), typeof(BasicControl)); public string Text1 { get { return GetValue(Text1
public static readonly DependencyProperty Text1Property =
DependencyProperty.Register("Text1", typeof(string),
typeof(BasicControl));
public string Text1
{
get { return GetValue(Text1Property).ToString(); }
set
{
SetValue(Text1Property, value.ToString());
OnPropertyChanged("Text2");
}
}
在本例中,Text2是另一个从Text1派生并显示在UI上的属性
运行此功能时,永远不会达到该功能。如何在每次更改依赖项属性时让代码运行?Clr属性只是DependencyProperty的包装,除非您直接在代码隐藏中获取/设置属性,否则它通常是通过传递的。要在属性更改时处理某些内容,需要提供一个
PropertyMetadata
,其中包含一些属性更改回调,如下所示:
public static readonly DependencyProperty Text1Property =
DependencyProperty.Register("Text1", typeof(string),
typeof(BasicControl), new PropertyMetadata(text1Changed));
//the text1Changed callback
static void text1Changed(DependencyObject o, DependencyPropertyChangedEventArgs e){
var bc = o as BasicControl;
if(bc != null) bc.OnPropertyChanged("Text2");
}
@金的回答很好,我想补充一些你应该知道的信息:
- 如果您只想通过dp支持属性并提供默认值
值,使用属性元数据
- 如果要指定动画行为,请使用
UIPropertyMetadata
- 但是如果某些属性影响wpf框架级别的东西,例如元素
布局、父布局或数据绑定,请使用
FrameworkPropertyMetadata
- 如果要指定动画行为,请使用
在实现属性以使用依赖项属性注册时,您可以在msdn上查看详细信息,抵制使用逻辑设置访问器的诱惑 换句话说,只有在过程代码中设置了属性时,才会调用
set
访问器。当使用XAML、数据绑定等设置属性时,WPF直接调用SetValue
。这就是函数无法访问的原因。。。这就是为什么King King提到,您所拥有的只是一个.NET属性包装器
解决方案可以是在属性更改时运行触发器。查看更多信息、选项和示例