按Arnaud Weil《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 theClickevent 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'sToggleBaseCommand, just like the originalCommandbinding.CommandParameter: We bind this to the ToggleButton'sIsCheckedproperty usingRelativeSourceto 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

