2010-04-01 52 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 2010-04-01 19:08:35

+0

如果你的意思是跨越多種控制類型(標籤,按鈕等),我會用附加的行爲來做到這一點。如果您的意思是在相同控件類型的不同實例之間重複使用,則應該使該樣式成爲資源。 – 2010-04-01 19:26:29

+0

附加行爲。謝謝Scott,你真棒。 – tim 2010-04-01 19:37:12

9

A「更清潔」的解決方案將是

<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中找到ComboBox的IsSelected屬性。 – 2013-11-04 02:44:22

+0

這是一個ComboBoxItem屬性@ShantanuGupta – edvaldig 2013-11-05 15:41:57