WPF 基础MvvM绑定的使用
首先在项目内定义三个文件夹(个人习惯)
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>
点击查看代码
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;
}
}
}
本文作者:ZhangQi777
本文链接:https://www.cnblogs.com/ZhangQi777/p/18140687
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
合集:
WPF
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步