私は、MVVM パターンを使用して WPF で C# を学習している学生です。最近、私はアプリケーションのアート (カスタム スプラッシュ スクリーン) に取り組んでいます。コードビハインドなしでこれを行う良い方法をウェブで検索してきました。残念ながら、何日も経っても満足のいく方法が見つかりませんでした。次に、自分のビューのコンストラクターにある 1 行のコードだけを使用して、自分でそれを行う方法を考えるようになりました。それでもコードをテスト可能にし、コードをビューから分離します。問題は、私がやろうとしていることを行うためのより良い方法があるかどうかです:
ViewModel のインターフェイス
public interface IPreventCloseViewModel
{
bool PreventClose { get; set; }
}
ビューの拡張機能
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;
}
};
}
}
}
ビューの分離コード
public partial class SplashScreen
{
public SplashScreen()
{
InitializeComponent();
this.PreventCloseViewModel();
}
}