ToggleButton EventTriggerBehavior- 将图像绑定到切换按钮的背景

ToggleButton EventTriggerBehavior- binding image to background of togglebutton

我的 xaml 中有以下代码:

<ToggleButton x:Name="play"    Command="{Binding OnPlayButton}" CommandParameter="{Binding ElementName=media , Mode=TwoWay}"  HorizontalAlignment="Left" Margin="573,638,0,0" VerticalAlignment="Top" Height="50" Width="50">
    <Image Name="MyImage"  Source="Images/Control/Play.png"/>
    <interactivity:Interaction.Behaviors>
        <core:EventTriggerBehavior EventName="Checked">
            <core:ChangePropertyAction  PropertyName="MyImage" Value="{Binding Source=Images/Control/Pause.png}" />
        </core:EventTriggerBehavior>
        <core:EventTriggerBehavior EventName="Unchecked">
            <core:ChangePropertyAction   PropertyName="MyImage" Value="{Binding Source=Images/Control/Play.png}" />
        </core:EventTriggerBehavior>
    </interactivity:Interaction.Behaviors>
</ToggleButton>

我想要实现的是在单击时将切换按钮的背景更改为 pause.png,再次单击时将其更改为 play.png。我在 xaml 中遇到异常,这是正确的方法吗?

您不能使用 PropertyName="MyImage",因为 "MyImage" 是控件的名称,而不是 ToggleButton 的 属性!

做你想做的最简单的方法是一个接一个地添加两个图像并根据控件状态改变可见性:

<ToggleButton x:Name="play">
    <Image Source="Images/Control/Play.png" Visibility="{Binding IsChecked, ElementName=play, Converter={StaticResource BooleanToVisibilityConverter}" />
    <Image Source="Images/Control/Stop.png" Visibility="{Binding IsChecked, ElementName=play, Converter={StaticResource InverterBooleanToVisibilityConverter}" />
</ToggleButton>

在上面的示例中,我使用了两个转换器实例来将 bool 值转换为 Visibility 值。您可以自己编写或只使用第 3 方,例如 Cimbalino Toolkit 中的 BooleanToVisibilityConverter

你几乎已经掌握了行为。但是 PropertyName 不是 Image,而是 SourceTargetObjectMyImage

您的代码应如下所示。

<ToggleButton HorizontalAlignment="Center" VerticalAlignment="Center" IsChecked="True">
    <Interactivity:Interaction.Behaviors>
        <Core:EventTriggerBehavior EventName="Checked">
            <Core:ChangePropertyAction TargetObject="{Binding ElementName=MyImage}" PropertyName="Source" Value="Images/Control/Pause.png" />
        </Core:EventTriggerBehavior>
        <Core:EventTriggerBehavior EventName="Unchecked">
            <Core:ChangePropertyAction TargetObject="{Binding ElementName=MyImage}" PropertyName="Source" Value="Images/Control/Play.png"/>
        </Core:EventTriggerBehavior>
    </Interactivity:Interaction.Behaviors>
    <Image x:Name="MyImage" Source="Images/Control/Play.png" Width="100" Height="100"/>
</ToggleButton>

祝你好运。