by Geert
18. November 2011 11:16
Catel contains lots of behaviors that are very useful. For more information about behaviors, see the documentation. However, this series of blog posts with “Behaviors in the spotlight” will put one behavior in the spotlights. All behaviors in Catel are compatible with WPF, Silverlight and Windows Phone 7.
Below is a screenshot of the example application that can be found at http://catelexamples.codeplex.com that contains an example of all behaviors.

This time, the Focus behavior is the one that is in the spotlights.
Setting the focus when the control loads
The easiest and default method is to set the focus when the associated control is loaded. In WPF, this is immediately when the control is focused. In Silverlight, there is a delay of 500 milliseconds by default, otherwise the focus is not set correctly.
1: <ListBox ItemsSource="{Binding PersonCollection}" SelectedItem="{Binding SelectedPerson}">
2: <i:Interaction.Behaviors>
3: <catel:Focus />
4: </i:Interaction.Behaviors>
5: </ListBox>
Setting the focus when a specific property has changed
It is possible to set the focus when a specific event occurs. For example, when the layout root gets a MouseEnter event, the focus must be set on a specific control. This can be done via the following code:
1: <ListBox ItemsSource="{Binding PersonCollection}" SelectedItem="{Binding SelectedPerson}">
2: <i:Interaction.Behaviors>
3: <catel:Focus FocusMoment="Event" Source="{Binding ElementName=layoutRoot}" EventName="MouseEnter" />
4: </i:Interaction.Behaviors>
5: </ListBox>
Setting the focus when a specific event has occurred
It is possible to set the focus when a specific property changes. For example, when a value is set, the focus must move on to a new control. This can be done via the following code:
1: <ListBox ItemsSource="{Binding PersonCollection}" SelectedItem="{Binding SelectedPerson}">
2: <i:Interaction.Behaviors>
3: <catel:Focus FocusMoment="PropertyChanged" Source="{Binding }" PropertyName="MyProperty" />
4: </i:Interaction.Behaviors>
5: </ListBox>
Demonstration video
This video demonstrates the different modes of the behavior.
Download the demo
You can download the demo here:
Behaviors demo.zip (598.50 kb) [Downloads: 89]