zniwalla
zniwalla

Reputation: 387

Closing popup with button in child usercontrol

I'm dealing with a popup which has a usercontrol as a child. This is done in a XAML file in UWP using Visual Studio 2015.
In my usercontrol resides a button with which I would like to close the parenting popup. I can't seem to achieve this - I've tried several options and the closest was by using a relay command. It should be mentioned that the popup pops up as supposed to.
Here is the popup with usercontrol child. No namespace problems, since the popup is working.
Here is the button in the usercontrol.

What should my approach be? I'm using ViewModels (MVVM desing) for this, and both usercontrol have access to the same instance of a ViewModel class.

Cheers!

Upvotes: 0

Views: 1492

Answers (1)

Ahmad
Ahmad

Reputation: 1524

have a look at https://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.popup.isopen(v=vs.110).aspx . You bind the Popup.IsOpen to a property in your view model ... the button sets the property to false.

<Popup IsOpen="{Binding ViewModel.IsOpen}" >
  ...
</Popup>

In the ViewModel you define a command that you can attach to AddCriteria button as such:

private ICommand _AddCriteriaCommand;
  public ICommand AddCriteriaCommand
  {
     get
     {
        return _AddCriteriaCommand;
     }
     set
     {
        _AddCriteriaCommand = value;
     }
  }

And you initiate this command in the constructor or the getter of AddCriteriaCommand to a RelayCommand... as such

public VMConstructor(...)
{
    _AddCriteriaCommand = new RelayCommand(execute => ClosePopup(), canExecute => true);
}

private void ClosePopup()
{
   _IsOpen = false;
}

in your xaml assign the commadn to the AddCriteria button , something like

<local:AddCrteria Command="{Binding AddCriteriaCommand}" />

For the popup you simply create a property for it with change notification as such:

private bool _isOpen;
public bool IsOpen
{
  get { return _isOpen; }
  set
  {
    if (_isOpen == value) return;
    _isOpen = value;
    RaisePropertyChanged("IsOpen");
  }
}

and finally bind the IsOpen property of the Popup control to that of the ViewModel as such:

IsOpen="{Binding IsOpen}"

And that should be it ... good luck.

Upvotes: 2

Related Questions