【问题标题】:WPF Triggers: Changing an out-of-scope control's style in a triggerWPF 触发器:在触发器中更改超出范围的控件样式
【发布时间】:2023-03-07 00:56:01
【问题描述】:

我无法在 XAML 中找到解决此问题的方法:

当左侧按钮的IsMouseOver 为真时,我想将右侧按钮的宽度设置为某个值。我不知道该放在哪里:在其中一个按钮的样式或模板中,或者在网格上的样式中。有没有可能?

<Border Style="{StaticResource ContentBodyStyle}" x:Name="Border" >
    <Grid Width="Auto" Height="Auto" Style="{DynamicResource GridStyle1}">
        <Grid.ColumnDefinitions>
        <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Button Margin="0,0,0,0" Content="Button" Grid.Row="0" x:Name="BtnLeft" Style="{DynamicResource ButtonStyle1}"/>
        <Button Margin="0,0,0,0" Content="Button" Grid.Column="1" x:Name="BtnRight" Width="0"/>
    </Grid>
</Border>

谢谢

【问题讨论】:

    标签: c# wpf data-binding .net-3.5 triggers


    【解决方案1】:

    我不确定您是否可以为控件范围之外的控件设置属性,并为其分配样式。即使有可能,这样做似乎也不对。 你可以在你的场景中做的是使用事件触发器和故事板,在它们对两个按钮可见的任何地方定义。这是一个如何修改 BtnLeft 的示例,尽管我更愿意将情节提要放在树上一点以便在必要时允许重用:

    <Button Margin="0,0,0,0" Content="Button" Grid.Row="0" x:Name="BtnLeft" Style="{DynamicResource ButtonStyle1}">
        <Button.Resources>
            <Storyboard x:Key="OnMouseEnter1">
                <DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
                    Storyboard.TargetName="BtnRight"
                    Storyboard.TargetProperty="Width">
                    <SplineDoubleKeyFrame KeyTime="00:00:00.5" Value="75"/>
                </DoubleAnimationUsingKeyFrames>
            </Storyboard>
            <Storyboard x:Key="OnMouseLeave1">
                <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" 
                    Storyboard.TargetName="BtnRight" 
                    Storyboard.TargetProperty="Width">
                    <SplineDoubleKeyFrame KeyTime="00:00:00.5" Value="0"/>
                </DoubleAnimationUsingKeyFrames>
            </Storyboard>
        </Button.Resources>
        <Button.Triggers>
            <EventTrigger RoutedEvent="Mouse.MouseEnter" SourceName="BtnLeft">
                <BeginStoryboard Storyboard="{StaticResource OnMouseEnter1}"/>
            </EventTrigger>
            <EventTrigger RoutedEvent="Mouse.MouseLeave" SourceName="BtnLeft">
                <BeginStoryboard Storyboard="{StaticResource OnMouseLeave1}"/>
            </EventTrigger>
        </Button.Triggers>
    </Button>
    

    您可以使用 MouseEnter 和 MouseLeave 事件来代替 IsMouseOver 属性。这应该会为您提供相同的功能。

    编辑:当在按钮范围内定义触发器时,EventTrigger 中的 SourceName 属性可以省略。

    【讨论】:

      猜你喜欢
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多