在 System.Windows.Forms.Button 中有一个 DialogResult 属性,那么在 System.Windows.Controls.Button (WPF) 中该属性在哪里?
在 System.Windows.Forms.Button 中有一个 DialogResult 属性,那么在 System.Windows.Controls.Button (WPF) 中该属性在哪里?
虽然没有内置的Button.DialogResult属性,但是您可以使用一个简单的附加属性自己创建(如果需要):
public class ButtonHelper
{
// Boilerplate code to register attached property "bool? DialogResult"
public static bool? GetDialogResult(DependencyObject obj) { return (bool?)obj.GetValue(DialogResultProperty); }
public static void SetDialogResult(DependencyObject obj, bool? value) { obj.SetValue(DialogResultProperty, value); }
public static readonly DependencyProperty DialogResultProperty = DependencyProperty.RegisterAttached("DialogResult", typeof(bool?), typeof(ButtonHelper), new UIPropertyMetadata
{
PropertyChangedCallback = (obj, e) =>
{
// Implementation of DialogResult functionality
Button button = obj as Button;
if(button==null)
throw new InvalidOperationException(
"Can only use ButtonHelper.DialogResult on a Button control");
button.Click += (sender, e2) =>
{
Window.GetWindow(button).DialogResult = GetDialogResult(button);
};
}
});
}
这将允许您编写:
<Button Content="Click Me" my:ButtonHelper.DialogResult="True" />
并获得相当于WinForms的行为(单击按钮会导致对话框关闭并返回指定的结果)
在 WPF 中没有 Button.DialogResult
。 您只需将 Window
的 DialogResult
设置为true或false:
private void buttonOK_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}
请确保您使用ShowDialog
而不是Show
来显示表单。如果您使用后者,将会引发以下异常:
未处理的InvalidOperationException
只有在创建并显示为对话框后才能设置DialogResult。
MessageBoxResult result = MessageBox.Show("","");
if (result == MessageBoxResult.Yes)
{
// CODE IN HERE
}
else
{
// CODE IN HERE
}
MessageBox.Show("", "")
不会显示是|否按钮。 - qJake