Pat
Pat

Reputation: 668

Window Binding to UserControl ViewModel

I need help with binding a window to a user control view model. Here's my user control, nice and simple.

<UserControl x:Class="WindowBindTest.UserControlTest"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         xmlns:ViewModel="clr-namespace:WindowBindTest.UserControlViewModel"
         d:DesignHeight="300" d:DesignWidth="300">
<UserControl.DataContext>
<ViewModel:UserControlViewModel></ViewModel:UserControlViewModel>
</UserControl.DataContext>
<Grid>            
</Grid>
</UserControl>

Here's my view model

namespace WindowBindTest
{
    public class UserControlViewModel
    {
        public Window hostWindow { get; set; }|
        public UserControlViewModel()
        {
            // I want to set the host window
            // If something isn't defined then close the host window.
        }    

    }
}

I could use a button to close the window but what if I didn't want to use a button. Is there a way to do that? Could I pass in the parent window into the constructor?

Upvotes: 1

Views: 599

Answers (1)

MoonKnight
MoonKnight

Reputation: 23833

You can do this in MVVM but you will need to use a service. In fact, this is where MVVM is weak (without using a framework such as Prism et al.). The following is a link to disore's DialogService class on CodeProject. it is awesome, but it will take time to get to grips with how it works.

The above library will enable you to close a View from a ViewModel.

I hope this helps.

Upvotes: 2

Related Questions