Chcoum
Chcoum

Reputation: 49

WPF : Get Parent property in Child ViewModel

I would like to Minimize my application by clicking on a UserControl button using MVVM.

Here is my ViewModel class:

public class HeaderViewModel : ViewModelBase, IHeaderViewModel
{
    public DelegateCommand MinimizeWindowCommand { get; set; }
    public HeaderViewModel(IHeaderView view) : base(view)
    {
        MinimizeWindowCommand = new DelegateCommand(OnMinimizeWindow);
    }
    private void OnMinimizeWindow()
    {
        /*
         * This is where I would like to minimize my Application
         * Something like MainWindow
         */
    }
}

When I click on my UserControl button, the MinimizeWindowCommand is called. In the OnMinimize() method, I wish to set the MainWindow visibility to Hidden.

By the way, I am using Prism and the UserControl is directly injected in the MainWindow as follow :

<Window
    xmlns:prism="http://prismlibrary.com/"
    [...]
    Title="Shell"
    x:Name="Shell">
    <ScrollViewer>
        <StackPanel>
            <ContentControl prism:RegionManager.RegionName="{x:Static infra:RegionNames.HeaderRegion}" />
        </StackPanel>
    </ScrollViewer>
</Window>

Thank you ! Chcoum

Upvotes: 0

Views: 729

Answers (1)

Chcoum
Chcoum

Reputation: 49

I found a solution and I took into account the comments.

With Prism Framework, you can use IEventAggregator to send messages between different part of your application. Here are the different steps with Prism.

Create a class that contains the reference of your event.

In that file, create a reference of your event as a class.

namespace MyNameSpace
{
    public class ViewUpdatedEvent : PubSubEvent<bool> { }
}

Publish this event in the ViewModel:

public class HeaderViewModel
{
    private IEventAggregator _eventAggregator;

    public DelegateCommand MinimizeWindowCommand { get; set; }

    public HeaderViewModel(IHeaderView view,IEventAggregator eventAggregator) : base(view)
    {
        _eventAggregator = eventAggregator;
        MinimizeWindowCommand = new DelegateCommand(OnMinimizeWindow);
    }

    private void OnMinimizeWindow()
    {
        _eventAggregator.GetEvent<ViewUpdatedEvent>().Publish(true);
    }
}

I send the parameter "true" to say that I want to reduce my Window.

Subscribe this event in the code-behind of the View:

public partial class Shell : Window
{
    public Shell(IEventAggregator eventAggregator)
    {
        InitializeComponent();
        eventAggregator.GetEvent<ViewUpdatedEvent>().Subscribe(OnMinimizeApp);
    }

    private void OnMinimizeApp(bool parameter)
    {
        if (parameter)
            this.Visibility = Visibility.Hidden;
    }
}

That's it. I'm falling in love with Prism ^^. Hope this help.

Upvotes: 1

Related Questions