如何为我的自定义wpf组件设置默认值? 我有一个Textfield属性为“公共保护保护{set; get;}”。保护是一个枚举:c# - 如何为wpf设计器设置自定义控件的默认值?
public class Field3270Attributes{
public enum Protection
{
PROTECTED,
UNPROTECTED,
AUTOSKIP
}
}
应AUTOSKIP但保护的默认值被列为因为它在枚举的第一个元素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;
}
}
谢谢但这只是我描述中的一个错误。我之前在autoskip中使用过它,并将其更改为protected,但问题是,如何设置默认值并确保从默认值到wpf设计器中的任何其他值的更改都被识别?如果没有回调,我可以更改值并且什么也没有发生,但我不想为每个值定义回调。 – Markus
当您注册DependencyProperty时,将自动为该属性创建一个Get/Set。您似乎会覆盖指向DependencyProperty的默认'TextField.Protection',并实现您自己的属性版本。尝试删除“Protection”属性的版本并查看它是否有效。 – Rachel
是的,我正在覆盖Protection属性的get/set,就像你在上面的代码中看到的那样。我将其更改为自动实现的属性: public Field3270Attributes.Protection Protection {set;得到; } 但这也行不通,我仍然需要回调,即使它只设置fields属性。 – Markus