我正在进入WPF,来自Winforms背景,我使用groupbox来显示和隐藏“面板”,具体取决于点击的菜单选项。这在设计时有一个噩梦,有多个重叠的组框。
WPF能解决这个问题吗?群组盒还有可行吗?或者有更好的解决方案吗?
答案 0 :(得分:4)
WPF GroupBox上有一个名为“Visibility”的属性(继承自UIElement),可以通过绑定在View Model中控制。
此Xaml片段显示GroupBox的可见性绑定到名为“MyGroupBoxVisibility”的属性...
<Grid>
<GroupBox Header="This and that" Visibility="{Binding MyGroupBoxVisibility}" Background="Plum"/>
</Grid>
包含“MyGroupBoxVisibility”的示例视图模型是......
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
}
此示例中包含两种方法,可以来回切换可见性。您可以使用此技术将WinForms内容传输到WPF中,并将其保留在MVVM中。
ETA:请注意,理解折叠和隐藏可见性之间的区别至关重要。有关说明,请参阅http://msdn.microsoft.com/en-us/library/system.windows.visibility(v=vs.110).aspx