为了使事情更美好,您可以使用像这样的附加属性:
<Button Content="OK" IsDefault="True" local:DialogBehaviours.OkButton="true"
Height="23" HorizontalAlignment="Left" Width="75" />
附加属性可以这样定义:
public class DialogBehaviours
{
/*
OkButton property.
An attached property for defining the Accept (OK) button on a dialog.
This property can be set on any button, if it is set to true, when enter is pressed, or
the button is clicked, the dialog will be closed, and the dialog result will be set to
true.
*/
public static bool GetOkButton(DependencyObject obj)
{return (bool)obj.GetValue(OkButtonProperty); }
public static void SetOkButton(DependencyObject obj, bool value)
{obj.SetValue(OkButtonProperty, value); }
public static readonly DependencyProperty OkButtonProperty =
DependencyProperty.RegisterAttached("OkButton", typeof(bool), typeof(Button), new UIPropertyMetadata(false, OnOkButtonPropertyChanged_));
static void OnOkButtonPropertyChanged_(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
if (!(obj is Button) || !(e.NewValue is bool))
return;
Button button = (Button)obj;
bool value = (bool)e.NewValue;
if (value)
button.Click += OnAcceptButtonClicked_;
else
button.Click -= OnAcceptButtonClicked_;
button.IsDefault = value;
}
static void OnAcceptButtonClicked_(object sender, RoutedEventArgs e)
{
if (!(sender is DependencyObject))
return;
Window parent = FindParent<Window>((DependencyObject)sender, (c) => true);
if (parent != null)
{
try { parent.DialogResult = true; }
catch (Exception)
{
parent.Close();
}
}
}
public static T FindParent<T>(DependencyObject obj, Predicate<T> predicate) where T : FrameworkElement
{
if (obj == null || predicate == null)
return null;
if (obj is T)
{
T control = (T)obj;
if (predicate(control))
return control;
}
DependencyObject parent = VisualTreeHelper.GetParent(obj);
return (parent == null) ? null : FindParent<T>(parent, predicate);
}
}