【发布时间】:2012-06-18 20:46:24
【问题描述】:
在 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 看起来不像是智能出来的。
【问题讨论】:
-
你说“app is crashed”什么是异常信息,stacktrace?
-
它说Can not cast the type MyNameSpace:TextBoxNewBehavior to type ...。但是如果我直接把它放在xaml中,没问题。困惑。
-
似乎没那么容易......但我在这里发现了同样的问题,所以我投票结束这个问题。
-
它不是重复的 - 这是用于 WPF
标签: silverlight silverlight-4.0 silverlight-5.0