Where is Button.DialogResult in WPF?

寵の児 提交于 2020-01-10 17:29:27

问题


In System.Windows.Forms.Button there is a property DialogResult, where is this property in the System.Windows.Controls.Button (WPF)?


回答1:


There is no built-in Button.DialogResult, but you can create your own (if you like) using a simple attached property:

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);
      };
    }
  });
}

This will allow you to write:

<Button Content="Click Me" my:ButtonHelper.DialogResult="True" />

and get behavior equivalent to WinForms (clicking on the button causes the dialog to close and return the specified result)




回答2:


There is no Button.DialogResult in WPF. You just have to set the DialogResult of the Window to true or false :

private void buttonOK_Click(object sender, RoutedEventArgs e)
{
    this.DialogResult = true;
}



回答3:


Just make sure that you've shown the form using ShowDialog rather than Show. If you do the latter you'll get the following exception raised:

InvalidOperationException was unhandled

DialogResult can be set only after Window is created and shown as dialog.




回答4:


MessageBoxResult result = MessageBox.Show("","");

if (result == MessageBoxResult.Yes)
{
// CODE IN HERE
}
else 
{
// CODE IN HERE
}


来源:https://stackoverflow.com/questions/1759372/where-is-button-dialogresult-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!