How to put style behavior for TextBox in Silverlight?

In Xaml, I can put custom behavior for a text field, for example:

<TextBox> <i:Interaction.Behaviors> <My:TextBoxNewBehavior/> </i:Interaction.Behaviors> </TextBox> 

I want all TextBox to have this behavior, so how do I put this behavior in an implicit style, for example?

 <Style TargetType="TextBox"> <Setter Property="BorderThickness" Value="1"/> .... </Style> 

Update: Thanks for the info. Try the method suggested below and the application crashes:

 <Setter Property="i:Interaction.Behaviors"> <Setter.Value> <My:TextBoxNewBehavior/> </Setter.Value> </Setter> 

My behavior is something like:

  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 does not look the same as in intelligence.

+4
source share
2 answers

Runtime Error Explanation

 <Setter Property="i:Interaction.Behaviors"> <Setter.Value> <My:TextBoxNewBehavior/> </Setter.Value> </Setter> 
  • You cannot attach behavior to other objects at the same time.
  • Interaction.Behaviors is a read-only collection that you cannot install.

Record

 <i:Interaction.Behaviors> <My:TextBoxNewBehavior/> </i:Interaction.Behaviors> 

means using the implicit collection syntax in XAML that calls Add () in the Behaviors collection.

Decision

Write your own nested property that you set with the style:

 <Setter Property="my:TextBoxOptions.UseMyBehavior" Value="true" /> 

Then you can create and set the behavior in the attached property code:

 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*/ } } 
+4
source

I solved this in a Windows 10 project, but it must be compatible with SL.

 <Page.Resources> <i:BehaviorCollection x:Key="behaviors"> <core:EventTriggerBehavior EventName="Tapped"> <core:InvokeCommandAction Command="{Binding SetModeToAll}" /> </core:EventTriggerBehavior> </i:BehaviorCollection> <Style TargetType="TextBlock" x:Key="textblockstyle"> <Setter Property="i:Interaction.Behaviors" Value="{StaticResource behaviors}"> </Setter> </Style> </Page.Resources> <Grid x:Name="LayoutRoot" Background="Transparent"> <TextBlock Text="Testing" Foreground="Red" FontSize="20" Style="{StaticResource textblockstyle}"> </TextBlock > </Grid> 

If I write in any other way, it will not work, but as a resource that works in the collection!

0
source

All Articles