WPF 基礎MvvM繫結的使用

1739401055發表於2024-04-17

首先在專案內定義三個資料夾(個人習慣)

ViewModel : 存放ViewModel類
UserView : 存放前端xaml頁面
Model : 存放實體類

1.建立WpfMvvmFoundationViewModel.cs

點選檢視程式碼
using System.ComponentModel;
namespace NewModel
{
    internal class WpfMvvmFoundationViewModel : INotifyPropertyChanged
    {
        /// <summary>
        /// 定義屬性
        /// </summary>
        public string _title;
        public string Title 
        {
            get { return _title; }
            set
            {
                if (_title!=value)
                {
                    _title = value;
                    OnPropertyChanged(nameof(Title));
                }
            }
        }

        /// <summary>
        /// 用於在屬性更改時通知訂閱者
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
        }

    }
}

2.建立WpfMvvmFoundation.xaml

點選檢視程式碼
<UserControl x:Class="NewModel.WpfMvvmFoundation"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:NewModel"
             mc:Ignorable="d" >
    <UserControl.DataContext>
        <local:WpfMvvmFoundationViewModel></local:WpfMvvmFoundationViewModel>
    </UserControl.DataContext>
    <Grid>
        <TextBlock Text="{Binding Title}"></TextBlock>
    </Grid>
</UserControl>

建立WpfMvvmFoundation.xaml.cs
點選檢視程式碼
using System.Windows.Controls;
namespace NewModel
{
    /// <summary>
    /// WpfMvvmFoundation.xaml 的互動邏輯
    /// </summary>
    public partial class WpfMvvmFoundation : UserControl
    {
        public WpfMvvmFoundationViewModel WpfMvvmFoundationViewModel;
        public WpfMvvmFoundation()
        {
            InitializeComponent();
            WpfMvvmFoundationViewModel = new WpfMvvmFoundationViewModel();
            this.DataContext = WpfMvvmFoundationViewModel;
        }
    }
}

相關文章