【转】[C#] WPF 使用 MVVM 的关闭窗体实现
转自:https://www.codenong.com/23613694
我在使用 WPF + Prism 写一个关闭窗体时,发现 MVVM 不太好使,查到码农家园里这个解决方案确实有效:
<Window ... xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"> <i:Interaction.Triggers> <i:EventTrigger EventName="Closing"> <command:EventToCommand Command="{Binding ClosingCommand}" PassEventArgsToCommand="True" /> </i:EventTrigger> </i:Interaction.Triggers>
然后在 VM 中这样:
public RelayCommand<CancelEventArgs> ClosingCommand { get; private set; } ctor() { ClosingCommand = new RelayCommand<CancelEventArgs>(args => args.Cancel = true); }
要使用Behavior 执行此操作,您可以使用 Behavior ,例如:
internal class CancelCloseWindowBehavior : Behavior<Window> { public static readonly DependencyProperty CancelCloseProperty = DependencyProperty.Register("CancelClose", typeof(bool), typeof(CancelCloseWindowBehavior), new FrameworkPropertyMetadata(false)); public bool CancelClose { get { return (bool) GetValue(CancelCloseProperty); } set { SetValue(CancelCloseProperty, value); } } protected override void OnAttached() { AssociatedObject.Closing += (sender, args) => args.Cancel = CancelClose; } }
<i:Interaction.Behaviors> <local:CancelCloseWindowBehavior CancelClose="{Binding CancelClose}" /> </i:Interaction.Behaviors>
浙公网安备 33010602011771号