18

System.Windows 中。Forms .Button中有一个属性DialogResult,这个属性在System.Windows 中是哪里。控制.Button (WPF)?

4

4 回答 4

32

没有内置的 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 等效的行为(单击按钮会导致对话框关闭并返回指定的结果)

于 2009-11-18T22:10:53.283 回答
22

WPF中没有Button.DialogResult。您只需将 的 设置DialogResultWindowtrue 或 false :

private void buttonOK_Click(object sender, RoutedEventArgs e)
{
    this.DialogResult = true;
}
于 2009-11-18T21:58:11.527 回答
1

只需确保您已使用ShowDialog而不是Show. 如果你做后者,你会得到以下异常:

InvalidOperationException 未处理

DialogResult 只能在 Window 创建并显示为对话框后设置。

于 2009-11-18T22:07:48.077 回答
-4
MessageBoxResult result = MessageBox.Show("","");

if (result == MessageBoxResult.Yes)
{
// CODE IN HERE
}
else 
{
// CODE IN HERE
}
于 2010-10-30T08:42:47.963 回答