溫馨提示×

mvvm框架在c#中的應(yīng)用案例

c#
小樊
81
2024-09-26 16:20:21
欄目: 編程語言

MVVM(Model-View-ViewModel)是一種軟件架構(gòu)設(shè)計模式,主要用于分離應(yīng)用程序的用戶界面(UI)和業(yè)務(wù)邏輯。在C#中,WPF(Windows Presentation Foundation)和UWP(Universal Windows Platform)是常用的實(shí)現(xiàn)MVVM框架的方式。以下是一個簡單的WPF應(yīng)用程序中應(yīng)用MVVM框架的案例:

  1. 首先,創(chuàng)建一個新的WPF應(yīng)用程序項(xiàng)目。

  2. 在項(xiàng)目中,創(chuàng)建一個Model類,例如Person

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
  1. 創(chuàng)建一個ViewModel類,例如PersonViewModel
public class PersonViewModel : INotifyPropertyChanged
{
    private Person _person;

    public PersonViewModel()
    {
        _person = new Person();
    }

    public string FirstName
    {
        get { return _person.FirstName; }
        set
        {
            _person.FirstName = value;
            OnPropertyChanged("FirstName");
        }
    }

    public string LastName
    {
        get { return _person.LastName; }
        set
        {
            _person.LastName = value;
            OnPropertyChanged("LastName");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
  1. 在MainWindow.xaml中,創(chuàng)建一個簡單的用戶界面,包括兩個文本框和一個按鈕:
<Window x:Class="MVVMExample.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:MVVMExample"
        mc:Ignorable="d"
        Title="MVVM Example" Height="200" Width="300">
    <Grid>
        <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
            <TextBox x:Name="txtFirstName" Text="{Binding FirstName}" />
            <TextBox x:Name="txtLastName" Text="{Binding LastName}" />
            <Button Content="Save" Click="btnSave_Click" />
        </StackPanel>
    </Grid>
</Window>
  1. 在MainWindow.xaml.cs中,設(shè)置數(shù)據(jù)上下文并處理按鈕點(diǎn)擊事件:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new PersonViewModel();
    }

    private void btnSave_Click(object sender, RoutedEventArgs e)
    {
        // 在這里處理保存邏輯,例如將數(shù)據(jù)保存到數(shù)據(jù)庫或文件
        MessageBox.Show("保存成功!");
    }
}

現(xiàn)在,當(dāng)用戶在文本框中輸入名字并點(diǎn)擊保存按鈕時,ViewModel中的屬性會更新,并觸發(fā)PropertyChanged事件。MainWindow.xaml會自動響應(yīng)這些更改并更新UI。

0