#867 – Controlling Whether a Popup Is Open Using Data Binding

You can control whether a popup is open by setting its IsOpen property from your code, using the name of the Popup control.  Another approach is to bind the IsOpen property to a boolean value and then to manipulate the boolean value to control whether the popup is open.

        <Popup IsOpen="{Binding PopupOpen}">
            <-- Content of Popup goes here -->

In your code-behind, you implement INotifyPropertyChanged and define the boolean PopupOpen property.

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            this.InitializeComponent();
            this.DataContext = this;
        }

        // INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        private void RaisePropertyChanged(string propName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }

        private bool popupOpen;
        public bool PopupOpen
        {
            get { return popupOpen; }
            set
            {
                popupOpen = value;
                RaisePropertyChanged("PopupOpen");
            }
        }

        private void question_MouseEnter(object sender, MouseEventArgs e)
        {
            PopupOpen = true;
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            PopupOpen = false;
        }

    }
Advertisement