0

私はWPFを初めて使用しますが、数日間インターネットを検索しても問題がわかりませんでした。

プログラムForegroundでプロパティを変更した後、IsMouseOverトリガーが機能しません。寛容であり、事前に感謝してください:)

<Style x:Key="ZizaMenuItem" TargetType="{x:Type Button}">
    <Setter Property="SnapsToDevicePixels" Value="True" />
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Setter Property="HorizontalContentAlignment" Value="Center"/>
    <Setter Property="Margin" Value="5,0,5,0"/>
    <Setter Property="Height" Value="30"/>
    <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Button}">
        <Label FontSize="14"  Content="{TemplateBinding Content}" Name="ZizaMenuItemText" />
        <ControlTemplate.Triggers>
          <Trigger Property="IsMouseOver" Value="True">
            <Setter TargetName="ZizaMenuItemText" Property="Foreground" Value="#ff0000"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

<StackPanel Height="30" Name="ZizaMenu" Orientation="Horizontal" Margin="0,12,0,0" VerticalAlignment="Top">
  <Label Content="ZIZA" FontSize="11" FontWeight="Bold" Foreground="Black" Height="25" Margin="20,0,10,0" />
  <Button Name="ZizaMenuInteresting" Click="ZizaMenuItemClicked" Content="ИНТЕРЕСНОЕ" Style="{StaticResource ZizaMenuItem}" />
  <Button Name="ZizaMenuBest" Click="ZizaMenuItemClicked" Content="ЛУЧШЕЕ" Style="{StaticResource ZizaMenuItem}" />
  <Button Name="ZizaMenuAuto" Click="ZizaMenuItemClicked" Content="АВТО" Style="{StaticResource ZizaMenuItem}" />
</StackPanel>
private void ZizaMenuItemClicked(object sender, RoutedEventArgs e)
{
    // get label object from template
    Button zizaMenuItem = (Button)sender;
    Label zizaMenuItemText = (Label)zizaMenuItem.Template.FindName("ZizaMenuItemText", zizaMenuItem);
    // set Foreground color for all buttons in menu
    foreach (var item in ZizaMenu.Children)
      if (item is Button)
        ((Label)(item as Button).Template.FindName("ZizaMenuItemText", (item as Button))).Foreground = Brushes.Black;
    // set desired color to clicked button label
    zizaMenuItemText.Foreground = new SolidColorBrush(Color.FromRgb(102, 206, 245));
}
4

2 に答える 2

2

これはひどいコードです。コントロール テンプレート内のコントロールをいじらないでください。Template.FindNameは、テンプレート化されているコントロールのみがそのパーツを取得するために内部的に呼び出す必要があるものであり、それらのみであり、他のすべては不確実であると見なされます。

プロパティ テンプレートを変更する必要がある場合は、それをバインドしてから、そのプロパティをインスタンスにバインドまたは設定します。優先順位に関しては、トリガーをオーバーライドするローカル値を作成しないようにする必要があります (それはあなたがしたことです)。Styleとを使用して、デフォルトSetterLabelをバインドできますForeground

<Label.Style>
    <Style TargetType="Label">
        <Setter Property="Foreground" Value="{TemplateBinding Foreground}"/>
    </Style>
</Label.Style>

Foregroundこれで、Button自体の を設定するだけで済みます。Trigger内部的には が優先されSetterます。

于 2012-07-29T04:35:15.710 に答える
1

依存関係プロパティの値の優先順位と関係があります。ローカル値は、テンプレート トリガーよりも優先されます。

詳細については、http: //msdn.microsoft.com/en-us/library/ms743230.aspxを参照してください。

于 2012-07-29T04:38:22.117 に答える