Displaying controls depending on user selection of a drop down list
I need to display different controls depending on what selection a user makes in a drop down. That i开发者_开发百科s, if the user makes a selection for a date, a date selection control should display, or text input box for text input... Or a set of controls for more complex selections.
So the idea is to create how ever many user controls, and then display the required one at the required time. I want something more elegant than faffing with 'visible true/false' properties.
You can achieve it using content control and data triggers. No need to play with Visibility.
Here is a sample which will give you clear idea. In the below sample i have taken a content control with combo box selected item as datacontext. XAML Code:
<StackPanel Orientation="Vertical" Width="150">
<ComboBox Name="Controls"></ComboBox>
<ContentControl DataContext="{Binding ElementName=Controls,Path=SelectedItem}">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Style.Triggers>
<DataTrigger Binding="{Binding}" Value="Date">
<Setter Property="Content">
<Setter.Value>
<DatePicker Height="30"></DatePicker>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding}" Value="Text">
<Setter Property="Content">
<Setter.Value>
<TextBox Height="30"></TextBox>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding}" Value="Button">
<Setter Property="Content">
<Setter.Value>
<Button Height="30"></Button>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding}" Value="Checkbox">
<Setter Property="Content">
<Setter.Value>
<CheckBox Height="30"></CheckBox>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</StackPanel>
Code Behind:
InitializeComponent();
List<string> controlTypes = new List<string> { "Date", "Text", "Button", "Checkbox" };
Controls.ItemsSource = controlTypes;
Note: For creating a sample i have used code behind... you can easily convert it to MVVM
I want something more elegant than faffing with 'visible true/false' properties.
:-) You will land up doing exactly that anyways....
This is too trivial ... any decent WPF related tutorial will help you with this...
Just for a quick start, you will have to use Binding
of ComboBox's SelectedItem
with Visibility
of all those controls you want to hide/show through a proper value converter.
精彩评论