Files
Shrlalgo.RvKits/ShrlAlgoToolkit.Mvvm/Behaviors/WindowCloseByButtonBehavior.cs

76 lines
2.3 KiB
C#
Raw Normal View History

2024-09-22 11:05:41 +08:00
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Xaml.Behaviors;
2025-04-24 20:56:44 +08:00
namespace ShrlAlgoToolkit.Mvvm.Behaviors;
2024-09-22 11:05:41 +08:00
//<Window x:Class="WpfApplication6.Window1"
// xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
// xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
// xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
// xmlns:local="clr-namespace:WpfApplication6"
// Title="Window1" Height="300" Width="300">
// <i:Interaction.Behaviors>
// <local:WindowCloseByButtonBehavior CloseButton="{Binding ElementName=closeButton}"/>
// </i:Interaction.Behaviors>
// <Grid>
// <Button Name="closeButton">CloseTrigger</Button>
// </Grid>
//</Window>
/// <summary>
/// 通过按钮点击,关闭窗口
/// </summary>
public class WindowCloseByButtonBehavior
: Behavior<Window>
{
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
nameof(Command),
typeof(ICommand),
typeof(WindowCloseByButtonBehavior)
);
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register(
nameof(CommandParameter),
typeof(object),
typeof(WindowCloseByButtonBehavior)
);
public static readonly DependencyProperty CloseButtonProperty = DependencyProperty.Register(
nameof(CloseButton),
typeof(Button),
typeof(WindowCloseByButtonBehavior),
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 = ((WindowCloseByButtonBehavior)d).AssociatedObject;
((Button)e.NewValue).Click += (s, e1) =>
{
var command = ((WindowCloseByButtonBehavior)d).Command;
var commandParameter = ((WindowCloseByButtonBehavior)d).CommandParameter;
command?.Execute(commandParameter);
window.Close();
};
}
}