开发者

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 t开发者_开发问答here a more elegant way to do such things in WPF?


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>


An alternative way is to use Popup Control

Try this tutorial.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜