2010-03-30 82 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