Saturday, January 5, 2013

How to put behavior in style for TextBox in Silverlight?

How to put behavior in style for TextBox in Silverlight?

In Xaml, I can put customized behavior for a textbox like:

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

I want to all TextBox has this behavior, so how to put this behavior in implicit style like?

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

Update: Thanks for info. Try the way as suggested below and the app is crashed:

<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 looks like not coming out in intelligence.

Answers & Comments...

Answer: 1

Explanation of runtime error

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

Writing

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

means using the implicit collection syntax in XAML, which calls Add() on the Behaviors collection.

Solution

Write you own attached property that you set using the style setter like this:

<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*/ } } 
by : Benjaminhttp://stackoverflow.com/users/1859442




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog