【发布时间】:2012-10-23 21:57:42
【问题描述】:
我有一个想要设置样式的自定义控件:
它只是一个继承自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.
谁能指出我正确的方向?
【问题讨论】:
-
Trigger只能应用于Style。在你的情况下styleListBoxItem不是this。 -
这么简单,我改了,不再收到错误,但是样式不起作用,有什么想法吗?
-
我没有看到你应用了样式。
-
@ChrisjanL 尝试设置 this.Style = styleListBoxItem;您是否有理由不只在 XAML 中定义样式?
-
@AndyB,控件只是一个.cs文件。没有xml。我希望将样式放在我的通用资源字典中,但它无权访问命名空间。