How to hide/show items in a stack panel?

2019-05-11 23:33发布

问题:

I have a wpf-mvvm application.

In that I have follwoing...

<Combo box>
item 1
item 2
</Combo box>
<stack pnel>
 <user control 1 />
 <user control 1 />
</stack pnel>

If user select "item 1" from combo, i need to display "user control 1" If user select "item 2" from combo, i need to display "user control 2"

In the viewmodel...I have an IList of those two combobox items.

what is the best way to hid/show items here ?

回答1:

You can actually remove the StackPanel completely, as you'll only be showing one UserControl at a time.

Once you've done that, you can use the technique described here to bind the ComboBox's value to the visibility of the UserControl. Just set the Visibility to Collapsed for the UserControl that's not chosen.

This allows you to handle this completely in XAML.



回答2:

There is always one more way to do it :-)

For example, you can do the very simple way: subscribe to SelectionChanged, check which is the currently selected item, and set the visibility of the items-to-be-hidden to collapsed.

There are more advanced ways, but I doubt that they are needed for this simple task. However, with the development of your code you might need to reconsider using this approach.



回答3:

This demonstrates two simple ways in which you can use a style to change the visibility on elements based on the selection in a combo box. The first style checks the SelectedIndex of the combo box, and the second checks its SelectedValue. I've populated the combo box with string objects in this example, but you can use SelectedValue with any kind of object, so long as you know what its ToString() method returns.

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:system="clr-namespace:System;assembly=mscorlib">
  <DockPanel>
  <ComboBox x:Name="comboBox" DockPanel.Dock="Top">  
   <system:String>Item 1</system:String>
   <system:String>Item 2</system:String>
  </ComboBox>
  <TextBlock DockPanel.Dock="Top" Text="This displays if Item 1 is selected">
   <TextBlock.Style>
    <Style TargetType="TextBlock">
      <Setter Property="Visibility" Value="Collapsed"/>
      <Style.Triggers>
       <DataTrigger Binding="{Binding ElementName=comboBox, Path=SelectedIndex}" Value="0">
        <Setter Property="Visibility" Value="Visible"/>
       </DataTrigger>
      </Style.Triggers>
    </Style>
   </TextBlock.Style>
  </TextBlock>
  <TextBlock DockPanel.Dock="Top" Text="This displays if Item 2 is selected.">
   <TextBlock.Style>
    <Style TargetType="TextBlock">
      <Setter Property="Visibility" Value="Collapsed"/>
      <Style.Triggers>
       <DataTrigger Binding="{Binding ElementName=comboBox, Path=SelectedValue}" Value="Item 2">
        <Setter Property="Visibility" Value="Visible"/>
       </DataTrigger>
      </Style.Triggers>
    </Style>
   </TextBlock.Style>
  </TextBlock>
  </DockPanel>
</Page>