我有一个DataForm,我将某些DataField的Visibility设置为Collapsed,当用户从ComboBox中选择一个选项时,某些DataFields应该再次可见。
基本上(粗糙的伪代码)。
OnComboBoxChange =
if this.index = 1 then
DataForm.Fields[1].Visibility = Visible
else
DataForm.Fields[2].Visibility = Visible
适用于MVVM模式的答案的奖励积分。
答案 0 :(得分:5)
这是一个使用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...
}
非常简单。我可能会尝试将我的属性命名为“模型”而不是“视图”,但这种约定并非完全不合适。
答案 1 :(得分:2)
在MVVM模式设置的上下文中,控件的可见性属于我可以看到的视图。无论如何,你的伪代码或多或少地完成了这项工作。以下是一些更具体的片段:
<UserControl>
<StackPanel>
<ComboBox x:Name="comboBox" SelectionChanged="comboBox_SelectionChanged"/>
<StackPanel x:Name="firstPanel" Orientation="Horizontal">
<TextBlock Text="First: "/>
<TextBox/>
</StackPanel>
<StackPanel x:Name="secondPanel" Orientation="Horizontal">
<TextBlock Text="Second: "/>
<TextBox/>
</StackPanel>
</StackPanel>
</UserControl>
和
public partial class MainPage : UserControl {
public MainPage() {
InitializeComponent();
this.comboBox.ItemsSource = new String[] { "First", "Second" };
this.comboBox.SelectedIndex = 0;
}
void comboBox_SelectionChanged(Object sender, SelectionChangedEventArgs e) {
ShowPanel((String) this.comboBox.SelectedItem);
}
void ShowPanel(String name) {
if (name == "First") {
this.firstPanel.Visibility = Visibility.Visible;
this.secondPanel.Visibility = Visibility.Collapsed;
}
else {
this.firstPanel.Visibility = Visibility.Collapsed;
this.secondPanel.Visibility = Visibility.Visible;
}
}
}