[英]Dependency Property Default Value
I am new with WPF and dependency properties and my question might be totally newbie... 我是WPF和依赖属性的新手,我的问题可能是全新的...
I have the following dependency property: 我有以下依赖属性:
public static readonly DependencyProperty IsEditableProperty =
DependencyProperty.Register("IsEditable", typeof(bool), typeof(EditContactUserControl),
new FrameworkPropertyMetadata(false, OnIsEditablePropertyChanged));
public bool IsEditable
{
get { return (bool)GetValue(IsEditableProperty); }
set { SetValue(IsEditableProperty, value); }
}
private static void OnIsEditablePropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
EditContactUserControl control = source as EditContactUserControl;
bool isEditable = (bool)e.NewValue;
if (isEditable)
control.stackPanelButtons.Visibility = Visibility.Visible;
else
control.stackPanelButtons.Visibility = Visibility.Collapsed;
}
The problem is that I want to have the code in the OnIsEditablePropertyChanged
to be executed also for the default value of my property, which doesn't happen. 问题是我希望OnIsEditablePropertyChanged
的代码也可以执行我的属性的默认值,但这不会发生。
What am I doing wrong, or how should I do this in your opiniion? 我做错了什么,或者我应该如何在你的意见中做到这一点?
Thank you in advance. 先感谢您。
Instead of changing the visibility in code, you should Bind the Visibility property in XAML and use a boolean to Visibility Converter. 您应该在XAML中绑定 Visibility属性并使用布尔值到Visibility Converter,而不是更改代码中的可见性。
If you do this, it doesn't matter if the property is initialized or not. 如果执行此操作,则无论属性是否已初始化都无关紧要。
The OnPropertyChanged callback won't be called on startup: The "default" value is in fact never really "set". 启动时不会调用OnPropertyChanged回调:“默认”值实际上从未真正“设置”。 Default: The value of the property when it isn't set. 默认值:未设置时的属性值。
If you want to execute some code at control startup, put it in the ApplyTemplate method override (in the case of a TemplatedControl) or at the end of your constructor (in the case of a UserControl) 如果要在控制启动时执行某些代码,请将其放在ApplyTemplate方法覆盖中(在TemplatedControl的情况下)或在构造函数的末尾(在UserControl的情况下)
Avoid duplicating this code in the constructor and in the property changed callback: Put it in a common method called by both ie: 避免在构造函数和属性更改的回调中复制此代码:将它放在两者调用的公共方法中:
void OnIsEditableChangedImpl(bool newValue)
{
....
}
我认为一个更好的方法是在你的XAML中设置stackPanelButtons.Visibility = Visibility.Collapsed
也是默认的,在这种情况下你不需要在启动时运行所有这些代码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.