wpf mvvm 的样列程序
时间: 2023-08-25 14:05:52 浏览: 59
以下是一个简单的 WPF MVVM 样例程序,它使用了 Prism 库来实现 MVVM 框架。
首先,我们需要定义一个 ViewModel:
```csharp
using Prism.Commands;
using Prism.Mvvm;
namespace WpfApp1.ViewModels
{
public class MainWindowViewModel : BindableBase
{
private string _title = "Hello World";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
private DelegateCommand _changeTitleCommand;
public DelegateCommand ChangeTitleCommand =>
_changeTitleCommand ?? (_changeTitleCommand = new DelegateCommand(ExecuteChangeTitleCommand));
void ExecuteChangeTitleCommand()
{
Title = "New Title";
}
}
}
```
这个 ViewModel 包含一个名为 `Title` 的属性,以及一个名为 `ChangeTitleCommand` 的命令。
接下来,我们需要定义一个 View:
```xaml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
xmlns:viewModels="clr-namespace:WpfApp1.ViewModels"
prism:ViewModelLocator.AutoWireViewModel="True"
Title="{Binding Title}">
<Grid>
<Button Content="Change Title" Command="{Binding ChangeTitleCommand}" />
</Grid>
</Window>
```
这个 View 包含一个按钮,该按钮绑定到 ViewModel 中定义的 `ChangeTitleCommand` 命令。
最后,我们需要在 App.xaml.cs 中注册 Prism 库并启动应用程序:
```csharp
using Prism.Ioc;
using Prism.Unity;
using System.Windows;
using WpfApp1.Views;
namespace WpfApp1
{
public partial class App : PrismApplication
{
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
}
protected override Window CreateShell()
{
return Container.Resolve<MainWindow>();
}
}
}
```
这个样例程序非常简单,但它演示了如何使用 Prism 库来构建一个基本的 WPF MVVM 应用程序。