Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
922 views
in Technique[技术] by (71.8m points)

wpf - Use style trigger to set property of a nested object

I have a small polygon written on the large canvas. I want to highlight a polygon when mouse is moving over the canvas. The code is like this:

<UserControl ...>
  <Canvas Name="canvas" Height="22" Width="22">
      <Canvas.Resources>
          <Style TargetType="Canvas">
              <Style.Triggers>
                  <Trigger Property="IsMouseOver" Value="false">
                      <Setter Property="polygon.Stroke" Value="#EEEEEE"/>
                  </Trigger>
                  <Trigger Property="IsMouseOver" Value="true">
                    <Setter Property="polygon.Stroke" Value="Aqua"/>
                </Trigger>
              </Style.Triggers>
          </Style>
      </Canvas.Resources>
      <Polygon Points="11,1 16,6 16,16 11,21" Name="polygon">
              <Polygon.Fill>
                  <SolidColorBrush Color="#EEEEEE"/>
              </Polygon.Fill>
      </Polygon>
  </Canvas>
</UserControl>

However setter does not see the "polygon".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot use Setters like that, if you use this kind of notation the engine will look for an attached property, or if no Style.TargetType was set for a property on the type before the dot.

The easiest thing to do is probably applying a style to the polygon itself and using a DataTrigger which binds to the Canvas so you can trigger on its properties.

  <Polygon Points="11,1 16,6 16,16 11,21" Name="polygon">
       <Polygon.Fill>
           <SolidColorBrush Color="#EEEEEE"/>
       </Polygon.Fill>
       <Polygon.Style>
          <Style TargetType="{x:Type Polygon}">
             <Style.Triggers> 
                <DataTrigger
                   Binding="{Binding Path=IsMouseOver,
                                     RelativeSource={RelativeSource
                                     AncestorType={x:Type Canvas}}}"
                   Value="True">
                   <Setter Property="Stroke" Value="Red"/>
                </DataTrigger>
             </Style.Triggers>
          </Style>
       <Polygon.Style>
  </Polygon>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...