In my application i'm using prism and trying to implement the following concept:
There is a communication window that can have two possible user controls. I have the ViewModels for the window and the user controlls. In every user control i have some buttons. For some buttons i need to perform some logic in the ViewModel and when the logic is done, close the parent window. I tried to send the parant window as a command parameter like this:
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
And in the viewModel close the window using the following code:
// Create the command
OpenChannelCommand = new RelayCommand(OpenChannel, IsValidFields);
...
private void OpenChannel()
{
// do some logic...
CloseWindow();
}
private GalaSoft.MvvmLight.Command.RelayCommand<object> _closeCommand;
private GalaSoft.MvvmLight.Command.RelayCommand<object> CloseWindow()
{
_closeCommand = new GalaSoft.MvvmLight.Command.RelayCommand<object>((o) => ((Window)o).Close(), (o) => true);
return _closeCommand;
}
But still the window aren't closing.
EDIT:
The user control XAML code is:
<Button Content="Open Channel" Command="{Binding OpenChannelCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/>
The user control ViewModel code is:
public RelayCommand OpenChannelCommand { get; set; }
ctor()
{
OpenChannelCommand = new RelayCommand(OpenChannel, IsValidFields);
}
private void OpenChannel()
{
// logic
CloseWindow();
}
private GalaSoft.MvvmLight.Command.RelayCommand<object> CloseWindow()
{
_closeCommand = new GalaSoft.MvvmLight.Command.RelayCommand<object>((o) => ((Window)o).Close(), (o) => true);
return _closeCommand;
}
This is the full implementaion that i currently tried. When setting a breakpoint to the CloseWindow method it hits at the view modet initialization and after calling it again in the button click command is doesn't do a thing.
((Window)o).Close()is it breaking there? - bkardolOpenChannelCommandto a button than parameter (ref to the window) must be send to this command. You don't needCloseWindowto be a command. Just a function with a ptr to a window as a parameter. - Leonid Malyshev