如何在Silverlight中为TextBox设置行为风格? [英] How to put behavior in style for TextBox in Silverlight?
本文介绍了如何在Silverlight中为TextBox设置行为风格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在XAML中,我可以为文本框添加自定义行为,如下所示:
<TextBox>
<i:Interaction.Behaviors>
<My:TextBoxNewBehavior/>
</i:Interaction.Behaviors>
</TextBox>
我希望所有的TextBox都有这个行为,那么如何将这个行为隐含地表现出来呢?
<Style TargetType="TextBox">
<Setter Property="BorderThickness" Value="1"/>
....
</Style>
更新: 谢谢你的信息。按照下面的建议尝试,应用程序会崩溃:
<Setter Property="i:Interaction.Behaviors">
<Setter.Value>
<My:TextBoxNewBehavior/>
</Setter.Value>
</Setter>
我的行为类似于:
public class TextBoxMyBehavior : Behavior<TextBox>
{
public TextBoxMyBehavior()
{
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.KeyUp += new System.Windows.Input.KeyEventHandler(AssociatedObject_KeyUp);
}
void AssociatedObject_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
//....
}
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.KeyUp -= new System.Windows.Input.KeyEventHandler(AssociatedObject_KeyUp);
}
}
TextBoxMyBehavior看起来没有出现在智能领域。
推荐答案
运行时错误说明
<Setter Property="i:Interaction.Behaviors">
<Setter.Value>
<My:TextBoxNewBehavior/>
</Setter.Value>
</Setter>
- 不能同时将行为附加到不同的对象。
- Interaction.Behaviors是您无法设置的只读集合。
正在编写
<i:Interaction.Behaviors>
<My:TextBoxNewBehavior/>
</i:Interaction.Behaviors>
表示在XAML中使用隐式集合语法,它对Behaviors集合调用Add()。
解决方案
编写使用样式设置器设置的附加属性,如下所示:
<Setter Property="my:TextBoxOptions.UseMyBehavior" Value="true" />
然后您可以在附加的属性代码中创建和设置行为:
private static void OnUseMyBehaviorPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue.Equals(true))
Interaction.GetBehaviors(dependencyObject).Add(new TextBoxNewBehavior());
else { /*remove from behaviors if needed*/ }
}
这篇关于如何在Silverlight中为TextBox设置行为风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文