Skip to main content

CurrentWindowService

  • 3 minutes to read

The CurrentWindowService allows you to control the associated window at the View Model level. The CurrentWindowService implements the ICurrentWindowService interface.

Attach the Service

To control a current window from a ViewModel, use the CurrentWindowService. For this, attach the CurrentWindowService service to your View (window). You can do this in the following ways:

xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
...
<Grid>
    <Grid.DataContext>
        <local:ViewModel />
    </Grid.DataContext>
    <dxmvvm:Interaction.Behaviors>
        <dxmvvm:CurrentWindowService />
    </dxmvvm:Interaction.Behaviors>
    <Button Command="{Binding CloseCommand}"/>
</Grid>

You can attach the CurrentWindowService to any object within a window, like in the code sample above.

To attach the service to another window, use any of the following.

  • Pass the required window to the service’s Window property.
  • Pass any child object within the required window to the service’s WindowSource property.

In the code sample below, the CurrentWindowService is attached to the main window.

<dxmvvm:CurrentWindowService Window="{Binding Source={x:Static Application.Current}, Path=MainWindow}" />

Access the Service

Refer to the following topics for more information how to access a service in ViewModel.

Manage the Current Window

The ICurrentWindowService interface provides a set of members useful to manipulate (for example, close or hide it) the current window in code.

Name

Description

Activate()

Activates the associated window.

Close()

Closes the associated window.

Hide()

Hides the associated window.

WindowState

Gets or sets the associated window’s state.

Show()

Shows the hidden associated window.

The code sample below shows how to access the service from a ViewModel that is a DevExpress.Mvvm.ViewModelBase descendant and how to close the current window from code.

public class ViewModel : ViewModelBase {
    public ICommand CloseCommand { get; private set; }
    protected ICurrentWindowService CurrentWindowService { get { return GetService<ICurrentWindowService>(); } }

    public ViewModel() {
        CloseCommand = new DelegateCommand(Close);
    }

    void Close() {
        if (CurrentWindowService != null)
            CurrentWindowService.Close();
    }
}

If you want to perform certain actions at the ViewModel level when the parent window is closed or prevent a window from being closed, bind the CurrentWindowService’s ClosingCommand property to a corresponding command in your ViewModel.

<dxmvvm:Interaction.Behaviors>
    <dxmvvm:CurrentWindowService ClosingCommand="{Binding ClosingCommand}"/>
</dxmvvm:Interaction.Behaviors>
See Also