我有一个我想要样式的自定义控件:
它只是一个继承自TextBox和另一个接口的类,该接口只添加了一个额外的属性。
如何将样式应用于此自定义控件,以便在设置只读属性时,背景变为灰色?
public class DionysusTextBox : TextBox, IDionysusControl
{
public DionysusTextBox()
{
SetStyle();
}
#region IDionysusControl Members
public bool KeepReadOnlyState
{
get { return (bool)GetValue(KeepReadOnlyStateProperty); }
set { SetValue(KeepReadOnlyStateProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty KeepReadOnlyStateProperty =
DependencyProperty.Register("KeepReadOnlyState", typeof(bool), typeof(DionysusTextBox), new UIPropertyMetadata(true));
#endregion
#region Style
Style styleListBoxItem = new Style(typeof(DionysusTextBox));
Trigger triggerReadonly = new Trigger { Property = DionysusTextBox.IsReadOnlyProperty, Value = true };
private void SetStyle()
{
triggerReadonly.Setters.Add(new Setter(DionysusTextBox.BackgroundProperty, Brushes.Black));
this.Triggers.Add(triggerReadonly);
}
#endregion
}
上面是整个类的代码,我使用样式的方式似乎是合适的方式但是当我将此控件添加到设计器时,我得到以下错误:
Triggers collection members must be of type EventTrigger.
有人能指出我正确的方向吗?
答案 0 :(得分:4)
您可以重新定义依赖项属性的默认行为,特别是,您可以定义PropertyChangedCallback
s:
public class DionysusTextBox : TextBox, IDionysusControl
{
static DionysusTextBox()
{
//For the IsReadOnly dependency property
IsReadOnlyProperty.OverrideMetadata(
//On the type DionysusTextBox
typeof(DionysusTextBox),
//Redefine default behavior
new FrameworkPropertyMetadata(
//Default value, can also omit this parameter
null,
//When IsReadOnly changed, this is executed
new PropertyChangedCallback(
(dpo, dpce) =>
{
//dpo hold the DionysusTextBox instance on which IsReachOnly changed
//dpce.NewValue hold the new value of IsReadOnly
//Run logic to set the background here, you are on the UI thread.
//Example of setting the BorderBrush from ARGB values:
var dioBox = dpo as DionysusTextBox;
//Should always be true, of course, it's just my OCD ;)
if (dioBox != null)
{
dioBox.BorderBrush =
ColorConverter.ConvertFromString("#FFDDDDDD") as Color?;
}
})));
//For the BorderBrush property
BorderBrushProperty.OverrideMetadata(
//On the type DionysusTextBox
typeof(DionysusTextBox),
//Redefine default behavior
new FrameworkPropertyMetadata(
//Default value
ColorConverter.ConvertFromString("#FFDDDDDD") as Color?));
}
public DionysusTextBox()
{
SetStyle();
}
}
请小心: UIPropertyMetadata
!= FrameworkPropertyMetadata