using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Microsoft.Xaml.Behaviors; namespace Sai.Toolkit.Mvvm.Behaviors; // // // // // // // // /// /// 通过按钮点击,关闭窗口 /// public class CloseByButtonBehavior : Behavior { public static readonly DependencyProperty CommandProperty = DependencyProperty.Register( nameof(Command), typeof(ICommand), typeof(CloseByButtonBehavior) ); public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register( nameof(CommandParameter), typeof(object), typeof(CloseByButtonBehavior) ); public static readonly DependencyProperty CloseButtonProperty = DependencyProperty.Register( nameof(CloseButton), typeof(Button), typeof(CloseByButtonBehavior), new FrameworkPropertyMetadata(null, OnCloseButtonChanged) ); public ICommand Command { get => (ICommand)GetValue(CommandProperty); set => SetValue(CommandProperty, value); } public object CommandParameter { get => GetValue(CommandParameterProperty); set => SetValue(CommandParameterProperty, value); } public Button CloseButton { get => (Button)GetValue(CloseButtonProperty); set => SetValue(CloseButtonProperty, value); } private static void OnCloseButtonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var window = ((CloseByButtonBehavior)d).AssociatedObject; ((Button)e.NewValue).Click += (s, e1) => { var command = ((CloseByButtonBehavior)d).Command; var commandParameter = ((CloseByButtonBehavior)d).CommandParameter; command?.Execute(commandParameter); window.Close(); }; } }