因为乍一看很难找出正确的方法来做我们朋友建议的事情,所以我继续使用一个小示例(最佳实践)代码。
这就是Josh Smith展示的App.xaml.cs的外观。
namespace MyApplication
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
static App()
{
// Ensure the current culture passed into bindings is the OS culture.
// By default, WPF uses en-US as the culture, regardless of the system settings.
//
FrameworkElement.LanguageProperty.OverrideMetadata(
typeof(FrameworkElement),
new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var window = new MainWindow();
// To ensure all the other Views of a type Window get closed properly.
ShutdownMode = ShutdownMode.OnMainWindowClose;
// Create the ViewModel which the main window binds.
var viewModel = new MainWindowViewModel();
// When the ViewModel asks to be closed,
// close the window.
EventHandler handler = null;
handler = delegate
{
viewModel.RequestClose -= handler;
window.Close();
};
viewModel.RequestClose += handler;
// Allow all controls in the window to bind to the ViewModel by
// setting the DataContext, which propagates down the element tree.
window.DataContext = viewModel;
window.Show();
}
}
}
同样,归根结底,如何布局 MVVM 应用程序取决于您。