gpt4 book ai didi

silverlight - 如何在 Silverlight 中为 TextBox 设置行为样式?

转载 作者:行者123 更新时间:2023-12-01 01:17:47 25 4
gpt4 key购买 nike

在 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 编写您自己设置的附加属性,如下所示:
    <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 - 如何在 Silverlight 中为 TextBox 设置行为样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11056466/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com