【问题标题】:windows WPF and XAML button changingwindows WPF 和 XAML 按钮更改
【发布时间】:2023-05-28 04:26:01
【问题描述】:

我正在尝试播放/暂停Button。 单击Play Button 时,将绑定到StartStopWatch 命令。 然后Play Button 将更改为Pause Button,该Pause Button 将绑定到PauseStopWatch 命令。 我的问题是。我不知道如何保持它的风格并可以互换地改变它们。目前我有两个不同的按钮,但我想将它们合并在一起并将它们合二为一。 我的按钮如下。我想在MouseClick 上拥有它,它也会改变!谢谢!

<Button x:Name="StartButton" Style="{DynamicResource StartTimerButton}"
        Width="24" Height="24" Margin="5,0,5,0" ToolTip="Start Timer"
        Command="{Binding StartStopWatch}" VerticalAlignment="Center"/>

<Button x:Name="StopButton" Style="{DynamicResource StopTimerButton}"
        Width="20" Height="20" Margin="0,0,5,0" ToolTip="Stop Timer"
        Command="{Binding StopStopWatch}" VerticalAlignment="Center"/>

有人有什么建议吗?

【问题讨论】:

  • 请说明您想要达到的目标。您想动态切换按钮上的样式和工具提示(可以作为样式 BTW 的一部分)吗?
  • 当按钮被点击时,它会改变。例子。你有一个播放按钮。当您单击播放按钮时,它会变为暂停按钮。当您单击暂停按钮时,它会变为播放按钮。但是当它在播放时,它会绑定到命令播放。当它暂停时,它绑定到命令暂停。另外,我正在尝试在按钮上保持相同的样式。我有一个红色和绿色的按钮。红色 = 停止,绿色 = 走。

标签: wpf xaml button


【解决方案1】:

一种简单的方法是使用 ToggleButton 并利用其 Checked 和 UnChecked 状态。您可以基于此更改 ControlTemplate 主题 对于Command,为什么不能为StopWatch创建一个Single Command,并将true/false作为CommandParameter传递来区分执行

<ToggleButton Name="yourToggleButton"
    Command="{Binding StartStopCommand}"
    CommandParameter="{Binding ElementName= yourToggleButton, Path=IsChecked}"/>

【讨论】:

    【解决方案2】:

    如果您有一个可以处于两种状态的按钮,请考虑使用ToggleButton,并将您想要的所有内容绑定到它的IsChecked 属性。特别是,您可以根据IsChecked批发(使用转换器)绑定按钮的Style,或者您可以在样式中使用触发器来更改外观(包括工具提示),具体取决于IsChecked的值。

    【讨论】: