【发布时间】:2011-08-17 00:45:20
【问题描述】:
如何为我的自定义 wpf 组件设置默认值? 我有一个属性为“public Protection Protection{set;get;}”的文本字段。保护是一个枚举:
public class Field3270Attributes{
public enum Protection
{
PROTECTED,
UNPROTECTED,
AUTOSKIP
}
}
默认值应该是 autoskip 但 protected 在 wpf 设计器中列为默认值,因为它是枚举中的第一个元素。 在 Textfield 构造函数中设置保护没有帮助。 我试过 DependencyProperty 确实有效,但如果我想要除默认值以外的任何值都可以工作,我必须指定一个回调(setProtection)。 如果我不指定回调,则在 wpf 设计器中更改值无效。 有没有办法在不必为每个属性指定回调方法的情况下获得相同的行为?
public class Textfield{
public static readonly DependencyProperty ProtectionProperty =
DependencyProperty.Register("Protection",
typeof(Field3270Attributes.Protection),
typeof(Textfield3270),
new FrameworkPropertyMetadata(Field3270Attributes.Protection.PROTECTED, setProtection));
private static void setProtection(object sender, DependencyPropertyChangedEventArgs e)
{
Textfield field = (Textfield)sender;
field.Protection = (Field3270Attributes.Protection)e.NewValue;
}
private Field3270Attributes.Protection protection;
public Field3270Attributes.Protection Protection
{
get
{
return protection;
}
set
{
this.protection = value;
if (value == Field3270Attributes.Protection.UNPROTECTED)
{
this.IsReadOnly = false;
Background = Brushes.White;
}
else
{
this.IsReadOnly = true;
Background = Brushes.LightSteelBlue;
}
}
}
public Textfield3270()
{
this.Protection = Field3270Attributes.Protection.PROTECTED;
}
}
【问题讨论】: