× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Alternative to groupbox?

Codementor User
Feb 05, 2015
<p>The WPF GroupBox has a property on it called 'Visibility' (inherited from UIElement) which can be controlled in a View Model via binding.</p> <p>This Xaml fragment shows a GroupBox's visibility being bound to a property called 'MyGroupBoxVisibility'...</p> <pre><code>&lt;Grid&gt; &lt;GroupBox Header="This and that" Visibility="{Binding MyGroupBoxVisibility}" Background="Plum"/&gt; &lt;/Grid&gt; </code></pre> <p>A sample View Model which contains the 'MyGroupBoxVisibility' is...</p> <pre><code>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 } </code></pre> <p>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.</p> <p>ETA: Note that it's vital to understand the difference between Collapsed and Hidden visibilities. Please see <a href="http://msdn.microsoft.com/en-us/library/system.windows.visibility(v=vs.110).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.windows.visibility(v=vs.110).aspx</a> for an explanation</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/17762120/Alternative%20to%20groupbox?/17762331">Stack Overflow</a>.</p>
comments powered by Disqus