[英]WPF MVVM Code Behind Best Practices
我是一名學生,使用MVVM模式學習使用WPF的C#。 最近我一直致力於[我的應用程序的藝術(自定義啟動畫面),當我不希望它時,不應該關閉它。 我一直在網上尋找一個沒有代碼隱藏的好方法。 不幸的是,幾天后我仍然沒有找到令人滿意的方式。 然后我開始想到一種方法,在我的視圖的構造函數中只有一行代碼的幫助。 它仍然使我的代碼可測試並將代碼與View分離。 問題是,有沒有更好的方法來做我想做的事情:
我的ViewModel界面
public interface IPreventCloseViewModel
{
bool PreventClose { get; set; }
}
View的擴展名
public static class PreventCloseViewModelExtension
{
/// <summary>
/// Use this extension method in the constructor of the view.
/// </summary>
/// <param name="element"></param>
public static void PreventCloseViewModel(this Window element)
{
var dataContext = element.DataContext as IDisposable;
if (dataContext is IPreventCloseViewModel)
{
element.Closing += delegate(object sender, CancelEventArgs args)
{
if (dataContext is IPreventCloseViewModel)
{
args.Cancel = (dataContext as IPreventCloseViewModel).PreventClose;
}
};
}
}
}
View的代碼隱藏
public partial class SplashScreen
{
public SplashScreen()
{
InitializeComponent();
this.PreventCloseViewModel();
}
}
MVVM並不意味着您不能使用Code-Behind。
MVVM意味着您的應用程序邏輯不應該與UI元素綁定。
您可以很好地處理后面的代碼中的事件(例如Window.Closing
),以及“發送消息”或在ViewModel中執行方法以對此作出反應。
在這里,您不會通過將事件處理程序放在代碼中來破壞MVVM。 如果您放置的邏輯決定了應用程序是否可以在后面的代碼中關閉,那么您將破壞MVVM。 這是應用程序邏輯的責任,應用程序邏輯存在於ViewModels中,而不是View。
我通常有一個通用的Shell
類,它繼承Window
並執行類似的操作:
public Shell()
{
InitializeComponent();
this.Closing += (s,e) =>
{
var canClose = Content as ICanClose;
if (canClose != null)
e.Cancel = !canClose.CanClose;
}
}
這樣,如果它實現了將被考慮的接口,那么放入哪種視圖模型並不重要。
在外化邏輯方面沒有太多意義,並且在MVVM模式方面也很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.