Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DialogResult declaratively?

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

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

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

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

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

like image 654
darja Avatar asked Mar 30 '10 05:03

darja


1 Answers

You can do this with an attached behavior to keep your MVVM clean. The C# code for your attached behavior might look something like so:

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 the property in XAML with the code below:

<Button local:IsAccept="True">OK</Button>
like image 155
Dustin Campbell Avatar answered Nov 15 '22 09:11

Dustin Campbell