WPF报错:Style.Triggers区域内无法设置Source Name属性
解决WPF中“Source Name property cannot be set within Style. Triggers section”错误
错误原因
WPF的Style.Triggers不支持带SourceName的EventTrigger。因为Style是可复用资源,它无法确定SourceName指定的元素(比如你的myButton)所在的上下文,所以会触发这个错误。
解决方案1:将EventTrigger移到父容器的Triggers中
把触发逻辑从Style里抽出来,放到父容器(比如Window、Grid)的Triggers集合里,这样就能正确引用按钮名称了。完整代码示例:
<Window x:Class="YourNamespace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="450" Width="800"> <Grid> <Button x:Name="myButton" Content="点击变色" Margin="20"/> <Rectangle x:Name="myRectangle" Margin="121,163,0,248" HorizontalAlignment="Left" Width="33" Height="34" Fill="Blue"/> <!-- 父容器的Triggers --> <Grid.Triggers> <EventTrigger SourceName="myButton" RoutedEvent="Button.Click"> <BeginStoryboard> <Storyboard> <ColorAnimation Storyboard.TargetName="myRectangle" Storyboard.TargetProperty="Fill.Color" To="Orange" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever"/> </Storyboard> </BeginStoryboard> </EventTrigger> </Grid.Triggers> </Grid> </Window>
解决方案2:在Style中使用DataTrigger监听按钮状态
如果想把逻辑保留在Style里,可以通过绑定按钮的IsPressed属性,用DataTrigger触发动画。需要确保按钮和矩形在同一命名空间下,绑定能正常访问:
<Grid> <Button x:Name="myButton" Content="点击变色" Margin="20"/> <Rectangle Margin="121,163,0,248" HorizontalAlignment="Left" Width="33" Height="34"> <Rectangle.Style> <Style TargetType="Rectangle"> <Setter Property="Fill" Value="Blue"/> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=myButton, Path=IsPressed}" Value="True"> <DataTrigger.EnterActions> <BeginStoryboard> <Storyboard> <ColorAnimation Storyboard.TargetProperty="Fill.Color" To="Orange" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever"/> </Storyboard> </BeginStoryboard> </DataTrigger.EnterActions> </DataTrigger> </Style.Triggers> </Style> </Rectangle.Style> </Rectangle> </Grid>
注:如果需要按钮松开后停止动画,可以给DataTrigger添加ExitActions来停止故事板。
内容的提问来源于stack exchange,提问作者Jakob
相关产品推荐
相关产品推荐

