You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按Arnaud Weil《Learn WPF MVVM》规范将命令改写为事件

Converting ToggleButton Command Binding to Event-Based Implementation (per Learn WPF MVVM)

First, let's recap your original command-based ToggleButton implementation, which uses MVVM command binding to pass the IsChecked state to your view model:

<ToggleButton Margin="8 0 16 0" 
              Command="{Binding ToggleBaseCommand}" 
              CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=IsChecked}" />

To convert this to an event-driven approach (following the patterns in Arnaud Weil's Learn WPF MVVM), you'll use WPF's interactivity triggers to bridge the button's events to your view model command. Here's the completed implementation, fixing the truncated code you started:

First, ensure you have the necessary interactivity namespace declared in your root XAML element (e.g., Window or UserControl):

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

Then, update your ToggleButton with the event trigger setup:

<ToggleButton Margin="8 0 16 0"
              Content="Send commands to device"
              Style="{StaticResource MaterialDesignRaisedDarkButton}">
    <i:Interaction.Triggers>
        <!-- Listen for the Click event, which fires on every toggle (checked/unchecked) -->
        <i:EventTrigger EventName="Click">
            <i:InvokeCommandAction 
                Command="{Binding ToggleBaseCommand}"
                CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ToggleButton}, Path=IsChecked}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ToggleButton>

Key Details:

  • i:Interaction.Triggers: This collection lets you attach event-driven behavior to UI elements without writing code-behind, which aligns with MVVM principles.
  • EventTrigger: We target the Click event because it fires every time the ToggleButton's state changes (both when it's checked and unchecked), matching the original command's behavior.
  • InvokeCommandAction: This acts as a bridge between the UI event and your view model's ToggleBaseCommand, just like the original Command binding.
  • CommandParameter: We bind this to the ToggleButton's IsChecked property using RelativeSource to reference the button itself, identical to your original implementation.

This approach keeps your view and view model separated, which is a core tenet of MVVM as outlined in Learn WPF MVVM.

内容的提问来源于stack exchange,提问作者Chris Lawford

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:00:58