0

我有一个 DataForm,我将某些 DataFields 的 Visibility 设置为 Collapsed,当用户从 ComboBox 中选择一个选项时,某些 DataFields 应该再次可见。

基本上(粗略的伪代码)。

OnComboBoxChange = 
    if this.index = 1 then
        DataForm.Fields[1].Visibility = Visible
    else
        DataForm.Fields[2].Visibility = Visible

适用于 MVVM 模式的答案的加分。

4

2 回答 2

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...
}

很简单。我可能会尝试将我的属性命名为更多“模型”而不是“视图”,但这种约定并非完全不合适。

于 2009-08-03T16:48:21.287 回答
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;
    }
  }

}
于 2009-08-03T15:02:02.403 回答