FocusBehavior
- 2 minutes to read
FocusBehavior allows you to set the focus to a UI control without utilizing code-behind.
Focus On Startup
To set the focus when an associated control is loaded, define the FocusBehavior for the control as follows.
<UserControl
xmlns:dxmvvmi="using:DevExpress.WinUI.Mvvm.UI.Interactivity"
xmlns:dxmvvm="using:DevExpress.WinUI.Mvvm.UI"
...>
<TextBox Text="This control is focused on startup">
<dxmvvmi:Interaction.Behaviors>
<dxmvvm:FocusBehavior/>
</dxmvvmi:Interaction.Behaviors>
</TextBox>
</UserControl>
Focus On an Event or Property Change
To focus a control when an event occurs, specify the EventName property.
<TextBox Text="This control is focused on button click: ">
<dxmvvmi:Interaction.Behaviors>
<dxmvvm:FocusBehavior SourceName="button" EventName="Click"/>
</dxmvvmi:Interaction.Behaviors>
</TextBox>
<Button x:Name="button" Content="Click to focus the TextBox"/>
To focus a UI control when a specific property is changed, specify the FocusBehavior.PropertyName property.
<TextBox Text="This control is focused when data is loaded">
<dxmvvmi:Interaction.Behaviors>
<dxmvvm:FocusBehavior SourceObject="{Binding ViewModel}" PropertyName="IsDataLoaded"/>
</dxmvvmi:Interaction.Behaviors>
</TextBox>
The SourceObject and SourceName properties specify an object used to process an event or property change. The SourceObject can be set through binding. The SourceName is the name of a UI element.
Focus With a Delay
If the associated control shouldn’t be focused immediately once it’s loaded or the event specified in the EventName property occurs, specify the required delay using the FocusBehavior.FocusDelay property.
<TextBox Text="This control is focused with a delay">
<dxmvvmi:Interaction.Behaviors>
<dxmvvm:FocusBehavior SourceName="btn" EventName="Click" FocusDelay="0:00:01"/>
</dxmvvmi:Interaction.Behaviors>
</TextBox>