Создаем новое WPF приложение с Prism Unity (разделение проекта на папки Services, Views, ViewModels) | C#
последнее обновление: 14 мая 2024
Prism Unity использует pattern MVVM .
MVVM (Model-View-ViewModel) это модный шаблон программы где идет разделение на: Model , View , ViewModel
View - это представление (окошко с кнопками, списками, таблицами и т.д.)
ViewModel - связывает представление через механизм привязки данных .
Скачать пример
Шаг 1. Открываем Visual Studio
Шаг 2. Создаем новое WPF приложение
Пишем название проекта WpfPrism (название проекта может быть любым)
Приложение создалось
Шаг 3. Добавляем NuGet package Prism.Unity
Шаг 3. Создаем новую папку Views
Шаг 4. Переносим файлы: MainWindow.xaml и MainWindow.xaml.cs в папку Views
Получилось вот так:
Меняем файл MainWindow.xaml
Файл MainWindow.xaml
<Window x:Class="WpfPrism.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfPrism"
mc:Ignorable="d"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
Title="MainWindow" Height="450" Width="800" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ListView
ItemsSource="{Binding Customers}"
SelectedItem="{Binding SelectedCustomer}" />
<Button
Grid.Row="1" Width="80" Height="40"
Command="{Binding CommandLoad}"
Content="LOAD" />
</Grid>
</Window>
Шаг 5. Создаем новую папку ViewModels
Кладем файл MainWindowViewModel.cs внутри папки ViewModels
C#
Файл MainWindowViewModel.cs
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfPrism.ViewModels
{
public class MainWindowViewModel : BindableBase
{
private Services.ICustomerStore _customerStore = null;
public MainWindowViewModel(Services.ICustomerStore customerStore)
{
_customerStore = customerStore;
}
public ObservableCollection<string > Customers { get; private set; } =
new ObservableCollection<string >();
private string _selectedCustomer = null;
public string SelectedCustomer
{
get => _selectedCustomer;
set
{
if (SetProperty<string >(ref _selectedCustomer, value))
{
Debug.WriteLine(_selectedCustomer ?? "no customer selected" );
}
}
}
private DelegateCommand _commandLoad = null;
public DelegateCommand CommandLoad =>
_commandLoad ?? (_commandLoad = new DelegateCommand(CommandLoadExecute));
private void CommandLoadExecute()
{
Customers.Clear();
List <string > list = _customerStore.GetAll();
foreach (string item in list)
Customers.Add(item);
}
}
}
Вот так получится
Шаг 7. Создаем новую папку Services
Кладем файл CustomerStore.cs внутри папки Services
C#
Файл CustomerStore.cs
using System.Collections.Generic;
namespace WpfPrism.Services
{
public interface ICustomerStore
{
List <string > GetAll();
}
public class DbCustomerStore : ICustomerStore
{
public List <string > GetAll()
{
return new List <string >()
{
"cust 1" ,
"cust 2" ,
"cust 3" ,
};
}
}
}
Вот так получится
Шаг 8. Меняем файл App.xaml и файл App.xaml.cs
Файл App.xaml
<prism:PrismApplication
x:Class="WpfPrism.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfPrism"
xmlns:prism="http://prismlibrary.com/" >
<Application.Resources>
</Application.Resources>
</prism:PrismApplication>
C#
Файл App.xaml.cs
using Prism.Ioc;
using Prism.Unity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using WpfPrism.Services;
namespace WpfPrism
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : PrismApplication
{
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.Register<ICustomerStore, DbCustomerStore>();
containerRegistry.RegisterForNavigation<MainWindow, ViewModels.MainWindowViewModel>();
}
protected override Window CreateShell()
{
var w = Container.Resolve<MainWindow>();
return w;
}
}
}
Шаг 9. Перекомпилируем приложение и запустим
Запутим
Приложение работает
Скачать пример