2013-12-15 83 views
1

我來自C#winforms背景,我通常會在代碼中執行所有操作。 我有幾個標籤,我用作菜單。 當鼠標懸停在文本通過改變顏色:更改OnClick標籤顏色WPF

<Page.Resources> 
    <SolidColorBrush x:Key="normalColor" Color="White" /> 
    <SolidColorBrush x:Key="mouseOverColor" Color="Gold" /> 
    <Style TargetType="Label" x:Key="menuItemStyle"> 
     <Style.Triggers> 
      <Trigger Property="IsMouseOver" Value="False"> 
       <Setter Property="Foreground" Value="{StaticResource normalColor}"/> 
      </Trigger> 
      <Trigger Property="IsMouseOver" Value="True"> 
       <Setter Property="Foreground" Value="{StaticResource mouseOverColor}"/> 
      </Trigger> 
     </Style.Triggers> 
    </Style> 
</Page.Resources> 

     <Label x:Name="Label_Video1" Style="{StaticResource menuItemStyle}" Content="1.Video 1." FontSize="16" HorizontalAlignment="Left" Margin="25,74,0,0" VerticalAlignment="Top" MouseLeftButtonDown="Label_Video1_MouseLeftButtonDown" /> 
    <Label x:Name="Label_Video2" Style="{StaticResource menuItemStyle}" Content="2. Video 2." FontSize="16" HorizontalAlignment="Left" Margin="25,105,0,0" VerticalAlignment="Top" MouseDown="Label_Video2_MouseDown"/> 

當用戶點擊一個標籤,我希望它留certin顏色(在這種情況下,黃金)和所有其他人留在他們正常的顏色。所以如果一個標籤以前被點擊過,我點擊另一個標籤,它會從黃金變成白色等。

回答

2

當使用WPF時,你必須略有不同。我們知道Label控件不知道它被點擊的時間,它特別不知道什麼時候點擊了另一個Label元素......但有些控件可以。考慮它...一個RadioButton正是這種行爲。現在這是WPF 真的閃耀。

我們可以用RadioButton s,不爲他們提供了新的ControlTemplate,我們可以讓他們看起來純文本:

<Grid Background="Black"> 
    <Grid.Resources> 
     <Style TargetType="{x:Type RadioButton}"> 
      <Setter Property="Template"> 
       <Setter.Value> 
        <ControlTemplate TargetType="{x:Type RadioButton}"> 
         <TextBlock Text="{TemplateBinding Content}"> 
          <TextBlock.Style> 
           <Style TargetType="{x:Type TextBlock}"> 
            <Setter Property="Foreground" Value="White" /> 
            <Style.Triggers> 
<DataTrigger Binding="{Binding IsChecked, RelativeSource={RelativeSource AncestorType={ 
x:Type RadioButton}}}" Value="True"> 
    <Setter Property="Foreground" Value="Gold" /> 
</DataTrigger> 
<DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource 
AncestorType={x:Type RadioButton}}}" Value="True"> 
    <Setter Property="Foreground" Value="Gold" /> 
</DataTrigger> 
            </Style.Triggers> 
           </Style> 
          </TextBlock.Style> 
         </TextBlock> 
        </ControlTemplate> 
       </Setter.Value> 
      </Setter> 
     </Style> 
    </Grid.Resources> 
    <StackPanel Margin="5" Background="{x:Null}"> 
     <RadioButton Content="1.Video 1." /> 
     <RadioButton Content="2.Video 2." /> 
     <RadioButton Content="3.Video 3." /> 
    </StackPanel> 
</Grid> 

如果你不希望RadioButton使他能都聚集在一個StackPanel,那麼你可以使用給他們相同的GroupName屬性值,以確保他們仍然作爲一個組運行。

+0

謝謝你這樣做。但是,如果我的文字點擊或鼠標懸停在它上面,我想讓文字變成黃金。有沒有辦法,我可以或兩個觸發器? –

+0

我知道了我只是在以下內容中添加:

+0

對不起,我沒注意到其他要求。我相應地更新了我的答案。請注意,你應該使用我添加的'DataTrigger',它將與'RadioButton'一起使用,而不僅僅是'TextBlock' ...你會發現它效果更好。您還可以爲「IsPressed」屬性添加另一個「DataTrigger」,以突出顯示用戶何時實際點擊其中一個。 – Sheridan