using System.Windows; namespace MainShell.Common { public class WindowService { // 定义一个名为 DialogResult 的附加属性 public static readonly DependencyProperty DialogResultProperty = DependencyProperty.RegisterAttached( "DialogResult", typeof(bool?), typeof(WindowService), new PropertyMetadata(DialogResultChanged)); // 当此属性值改变时,调用 DialogResultChanged 方法 // 提供 Set 方法供外部设置附加属性的值 public static void SetDialogResult(UIElement element, bool? value) { element.SetValue(DialogResultProperty, value); } // 提供 Get 方法供外部获取附加属性的值 public static bool? GetDialogResult(UIElement element) { return (bool?)element.GetValue(DialogResultProperty); } // 当 DialogResult 附加属性的值改变时调用的回调方法 private static void DialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { // 确保附加属性应用在一个 Window 控件上,并且新的值是 bool 类型 if (d is Window window && e.NewValue is bool result) { // 设置窗口的 DialogResult window.DialogResult = result; // 关闭窗口 window.Close(); } } } }