2010-04-01 5 views
9

콤보의 특정 항목을 선택한 경우에만 레이블을 표시하려고합니다. 코드가이를 설명해야합니다.WPF 콤보 선택을 기반으로 한 UI 요소의 가시성

<ComboBox Name="comboMyCombo"> 
     <ComboBoxItem>Don't show the label</ComboBoxItem> 
     <ComboBoxItem>Show the label</ComboBoxItem> 
    </ComboBox> 

    <Label Visibility="Collapsed">This is my label 
     <Label.Style> 
      <Style> 
       <Style.Triggers> 
        <DataTrigger 
          Binding="{Binding ElementName=comboMyCombo, Path=SelectedValue}" Value="Show the label"> 
         <Setter Property="Label.Visibility" Value="Visible"></Setter> 
        </DataTrigger> 
       </Style.Triggers> 
      </Style> 
     </Label.Style> 
    </Label> 

답변

24

여기에는 두 가지 문제가 있습니다. 먼저 기본 표시 유형을 스타일에 지정해야합니다. 그러나 트리거를 바인딩하면 SelectedValue, ComboBoxItem 객체를 문자열 객체와 비교하므로 절대 작동하지 않습니다. 예제를 간단하게하기 위해 ComboBoxItem의 Tag 속성에 적절한 값을 배치했습니다. 비교의 실제 구현은 응용 프로그램의 특정 요구에 따라 달라질 수 있지만. 그것을 반복하지 않고 여러 컨트롤에서이 트리거를 다시 사용할 수있는 방법이있다 :

<ComboBox Name="comboMyCombo"> 
     <ComboBoxItem Tag="Hide">Don't show the label</ComboBoxItem> 
     <ComboBoxItem Tag="Show">Show the label</ComboBoxItem> 
    </ComboBox> 

    <Label>This is my label 
     <Label.Style> 
      <Style> 
       <Setter Property="Label.Visibility" Value="Collapsed"></Setter> 
       <Style.Triggers> 
        <DataTrigger 
         Binding="{Binding ElementName=comboMyCombo, Path=SelectedItem.Tag}" Value="Show"> 
         <Setter Property="Label.Visibility" Value="Visible"></Setter> 
        </DataTrigger> 
       </Style.Triggers> 
      </Style> 
     </Label.Style> 
    </Label> 
+0

것입니까? 이 선택 영역을 기반으로 숨기고 싶은 여러 컨트롤이 있습니다. 그들은 별도의 그리드 셀이므로 전체 스택 패널을 숨길 수는 없습니다. – tim

+0

여러 컨트롤 유형 (Label, Button 등)에 걸쳐 의미가있는 경우 첨부 된 동작으로이를 수행합니다. 동일한 컨트롤 유형의 서로 다른 인스턴스간에 재사용을 의미하는 경우 스타일을 리소스로 설정해야합니다. –

+0

연결된 동작입니다. Scott, 고맙습니다. – tim

9

A "깨끗한"솔루션은 BTW

<ComboBox> 
    <ComboBoxItem x:Name="iOne" Content="One"/> 
    <ComboBoxItem x:Name="iTwo" Content="Two"/> 
    <ComboBoxItem x:Name="iThree" Content="Three"/> 
</ComboBox> 

<Label Content="One is shown"> 
<Label.Style> 
    <Style TargetType="Label"> 
     <Setter Property="Visibility" Value="Hidden" /> 
     <Style.Triggers> 
      <DataTrigger Binding="{Binding ElementName=iOne, Path=IsSelected}" Value="True"> 
       <Setter Property="Visibility" Value="Visible"/> 
      </DataTrigger> 
     </Style.Triggers> 
    </Style> 
</Label.Style> 
</Label> 
+0

WPF에서 콤보 상자의 IsSelected 속성을 찾을 수 없습니다. –

+0

ComboBoxItem @ShantanuGupta의 속성입니다. – edvaldig

관련 문제