我仍然在尋找附加的行爲,並且不知道如何爲其中的單元測試編寫代碼。單元測試一個附加的行爲wpf
我從Sacha Barber的Cinch框架下面粘貼了一些代碼,允許通過附加行爲來關閉窗口。有人可以向我展示一個示例單元測試嗎?
謝謝!
Berryl
#region Close
/// <summary>Dependency property which holds the ICommand for the Close event</summary>
public static readonly DependencyProperty CloseProperty =
DependencyProperty.RegisterAttached("Close",
typeof(ICommand), typeof(Lifetime),
new UIPropertyMetadata(null, OnCloseEventInfoChanged));
/// <summary>Attached Property getter to retrieve the CloseProperty ICommand</summary>
public static ICommand GetClose(DependencyObject source)
{
return (ICommand)source.GetValue(CloseProperty);
}
/// <summary>Attached Property setter to change the CloseProperty ICommand</summary>
public static void SetClose(DependencyObject source, ICommand command)
{
source.SetValue(CloseProperty, command);
}
/// <summary>This is the property changed handler for the Close property.</summary>
private static void OnCloseEventInfoChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var win = sender as Window;
if (win == null) return;
win.Closing -= OnWindowClosing;
win.Closed -= OnWindowClosed;
if (e.NewValue == null) return;
win.Closing += OnWindowClosing;
win.Closed += OnWindowClosed;
}
/// <summary>
/// This method is invoked when the Window.Closing event is raised.
/// It checks with the ICommand.CanExecute handler
/// and cancels the event if the handler returns false.
/// </summary>
private static void OnWindowClosing(object sender, CancelEventArgs e)
{
var dpo = (DependencyObject)sender;
var ic = GetClose(dpo);
if (ic == null) return;
e.Cancel = !ic.CanExecute(GetCommandParameter(dpo));
}
/// <summary>
/// This method is invoked when the Window.Closed event is raised.
/// It executes the ICommand.Execute handler.
/// </summary>
static void OnWindowClosed(object sender, EventArgs e)
{
var dpo = (DependencyObject)sender;
var ic = GetClose(dpo);
if (ic == null) return;
ic.Execute(GetCommandParameter(dpo));
}
#endregion
cinch更進一步與繼電器命令通過烘烤你被稱爲測試成CommandSucceeded布爾屬性。您的文章有助於強制執行SetClose在一天結束時仍然是屬性設置器,即使它看起來不像更簡單的普通C#屬性設置器!這是我沒有看到的事情之一,對於我而言對DP /附加行爲並不直觀。歡呼 – Berryl
是的。編譯時,這些靜態的Get/Set方法被調用。與DP一樣:它跳過屬性包裝並直接在'DependencyObject'上調用'SetValue' /'GetValue'。很高興在Cinch聽到這個消息。這不是我已經讀過的。 –