这是一个使用 MVVM 的示例,它避免了代码隐藏(有争议的 MVVM 否-否):
<UserControl>
<StackPanel>
<ComboBox x:Name="comboBox" SelectionChanged="comboBox_SelectionChanged"/>
<StackPanel Orientation="Horizontal" Visibility="{Binding IsFirstFormShown}">
<TextBlock Text="First: "/>
<TextBox/>
</StackPanel>
<StackPanel Orientation="Horizontal" Visibility="{Binding IsSecondFormShown}">
<TextBlock Text="Second: "/>
<TextBox/>
</StackPanel>
</StackPanel>
</UserControl>
那么这是你的 ViewModel,
public class MyFormViewModel : INotifyPropertyChanged
{
private System.Windows.Visibility _isFirstShown;
public System.Windows.Visibility IsFirstFormShown
{
get { return _isFirstShown; }
set
{
_isFirstShown = value;
if (PropertyChanged != null )
{
PropertyChanged(this, new PropertyChangedEventArgs(value));
}
}
}
//TODO: implement the other property (writing code in this edit window makes me tired)
//hopefully you get the picture here...
}
很简单。我可能会尝试将我的属性命名为更多“模型”而不是“视图”,但这种约定并非完全不合适。