2010-03-30 80 views
7

在WinForms中,我们可以为按钮指定DialogResult。在WPF中,我们可以在XAML中声明只有取消按钮:WPF DialogResult声明?

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

对于其他人,我们需要赶上ButtonClick,写这样的代码:

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

我使用MVVM,所以我只为XAML代码视窗。但对于模态窗口,我需要编写这样的代码,我不喜欢这样。有没有一种更优雅的方式在WPF中做这样的事情?

+0

重复:http://stackoverflow.com/questions/ 501886/wpf-mvvm-newbie-how-view-model-close-the-form – 2010-07-24 21:52:31

+0

我曾经感觉这种关于在MVVM中使用代码的方式,但说实话,我认为在*后面的代码中设置单个标志是*最优雅的解决方案。为什么要对抗它。写一个复杂的附加行为是没有意义的。 – craftworkgames 2015-08-31 05:40:46

回答

2

你可以用attached behavior这样做来保持你的MVVM清洁。您的附加行为的C#代码可能看起来像这样:

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

您可以使用XAML属性与下面的代码:

<Button local:IsAccept="True">OK</Button> 
+0

我不知道他为什么不标记你的答案,但我为有用的MVVM样式接受按钮投票。交互行为可以做到这一点,但对于我来说这太简单了。 – Alan 2013-02-06 15:47:26