1

I'm diving into WPF, coming from a Winforms background where I used groupboxes to show and hide "panels" depending on what menu options were clicked. This was a bit of a nightmare at designtime having multiple overlapping groupboxes.

Does WPF solve this problem? Is the groupbox still the way to go? Or are there better solutions?

1
  • Not that it's relevant anymore, but UserControls would have been a better solution in WinForms. You can design them separately. Jul 20, 2013 at 13:00

1 Answer 1

4

The WPF GroupBox has a property on it called 'Visibility' (inherited from UIElement) which can be controlled in a View Model via binding.

This Xaml fragment shows a GroupBox's visibility being bound to a property called 'MyGroupBoxVisibility'...

<Grid>
    <GroupBox Header="This and that" Visibility="{Binding MyGroupBoxVisibility}" Background="Plum"/>
</Grid>

A sample View Model which contains the 'MyGroupBoxVisibility' is...

public class ViewModel : INotifyPropertyChanged
{
    public ViewModel()
    {
        HideTheGroupBox();
    }
    private void ShowTheGroupBox()
    {
        MyGroupBoxVisibility = Visibility.Visible;
    }
    private void HideTheGroupBox()
    {
        MyGroupBoxVisibility = Visibility.Collapsed;
    }
    private Visibility _myGroupBoxVisibility;
    public Visibility MyGroupBoxVisibility
    {
        [DebuggerStepThrough]
        get { return _myGroupBoxVisibility; }
        [DebuggerStepThrough]
        set
        {
            if (value != _myGroupBoxVisibility)
            {
                _myGroupBoxVisibility = value;
                OnPropertyChanged("MyGroupBoxVisibility");
            }
        }
    }
    #region INotifyPropertyChanged Implementation
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string name)
    {
        var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
    #endregion
}

This sample has two methods in it which toggle the visibility back and forth. You can use this technique to transfer your WinForms stuff into WPF and also keep it within MVVM.

ETA: Note that it's vital to understand the difference between Collapsed and Hidden visibilities. Please see http://msdn.microsoft.com/en-us/library/system.windows.visibility(v=vs.110).aspx for an explanation

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.