WPF DialogResult declaratively?

In WinForms, we can specify DialogResult for buttons. In WPF, we can only declare the Cancel button in XAML:

<Button Content="Cancel" IsCancel="True" /> 

For others, we need to catch ButtonClick and write code like this:

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

I use MVVM, so I only have XAML code for windows. But for modal windows, I need to write such code, and I don't like it. Is there a more elegant way to do such things in WPF?

+7
wpf modal-dialog
source share
2 answers

You can do this with sticky behavior so that your MVVM is clean. C # code for your applied behavior might look something like this:

 public static class DialogBehaviors { private static void OnClick(object sender, RoutedEventArgs e) { var button = (Button)sender; var parent = VisualTreeHelper.GetParent(button); while (parent != null && !(parent is Window)) { parent = VisualTreeHelper.GetParent(parent); } if (parent != null) { ((Window)parent).DialogResult = true; } } private static void IsAcceptChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { var button = (Button)obj; var enabled = (bool)e.NewValue; if (button != null) { if (enabled) { button.Click += OnClick; } else { button.Click -= OnClick; } } } public static readonly DependencyProperty IsAcceptProperty = DependencyProperty.RegisterAttached( name: "IsAccept", propertyType: typeof(bool), ownerType: typeof(Button), defaultMetadata: new UIPropertyMetadata( defaultValue: false, propertyChangedCallback: IsAcceptChanged)); public static bool GetIsAccept(DependencyObject obj) { return (bool)obj.GetValue(IsAcceptProperty); } public static void SetIsAccept(DependencyObject obj, bool value) { obj.SetValue(IsAcceptProperty, value); } } 

You can use this property in XAML with the code below:

 <Button local:IsAccept="True">OK</Button> 
+2
source share

An alternative way is to use Popup Control

Try the tutorial .

+1
source share

All Articles