2009-08-03 5 views
0

特定のDataFieldの表示をCollapsedに設定したDataFormがあり、ユーザーがComboBoxからオプションを選択すると、特定のDataFieldを再度表示する必要があります。Silverlight 3 DataForm、フィールドの表示/非表示方法

基本的に(ラフ擬似コードで)。

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

MVVMパターンに適用できる回答のボーナスポイント。

答えて

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

かなり簡単です。おそらく、私の物件をもう少し「モデル」と「ビュー」というものにしようとしますが、このコンベンションは完全に不適切なものではありません。

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

} 
関連する問題