Silverlight 3 DataForm, how to show / hide fields
-
10-07-2019 - |
Question
I've a DataForm which I have set the Visibility of certain DataFields to be Collapsed, and when the user selects an option from a ComboBox, certain DataFields should be made visible again.
Basically (in rough pseudocode).
OnComboBoxChange =
if this.index = 1 then
DataForm.Fields[1].Visibility = Visible
else
DataForm.Fields[2].Visibility = Visible
Bonus points for an answer that is applicable to a MVVM pattern.
Solution
Here's a sample using MVVM that avoids codebehind (debatable MVVM no-no):
<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>
Here's your ViewModel then,
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...
}
Pretty simple. I'd probably try and name my properties something a little more "Model" and less "View", but this convention is not entirely inappropriate.
OTHER TIPS
In the context of a MVVM pattern setting the visibility of controls belongs to the view as far as I can see. Anyway, you pseudocode does the job more or less. Here are some fragments that are a bit more concrete:
<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>
and
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;
}
}
}