How to hide / show items in the stack panel?

I have a wpf-mvvm application.

That I have the following ...

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

If the user selects "item 1" from combo, I need to display "user control 1", If the user selects "item 1" from combo, I need to display "user control 2"

In the viewmodel ... I have an IList of these two combo elements.

What is the best way to hide / show items here?

+3
source share
3 answers

You can completely remove it StackPanel, since you will only show one UserControl at a time.

, , ComboBox UserControl. Visibility Collapsed UserControl.

XAML.

+5

: -)

, : SelectionChanged, , , .

, , . .

+1

This demonstrates two simple ways that you can use a style to change the visibility of elements based on a selection in a combo box. The first style checks SelectedIndexthe combo boxes, and the second checks it SelectedValue. In this example, I filled in the combo box with string objects, but you can use it SelectedValuewith any kind of object if you know that its method ToString()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>
+1
source

Source: https://habr.com/ru/post/1789292/


All Articles