这个代码实现的功能是,按“测试”按钮,显示单词“Hello World”,它是WPF最核心的原理代码。用绑定控制数据,用命令代替事件。
XAML界面代码如下:
<Window x:Class="WpfApp2.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"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<Button Content="测试" Height="30" Width="100" Command="{Binding ShowCommand}"/>
<Label Content="{Binding Name}" HorizontalContentAlignment="Center"/>
</StackPanel>
</Window>
类代码如下:
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
namespace WpfApp2
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext=new ViewModel();
}
}
//继承INotifyPropertyChanged接口,用来实现界面跟随属性的改变而改变。
//之所以做成父类,是为了实现代码复用
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string propertyName="")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
//绑定数据源的类,包括属性和命令
public class ViewModel:ViewModelBase
{
public ViewModel()
{
ShowCommand = new MyCommand(ShowEvent);
}
private string name = "默认值";
public string Name { get { return name; } set { name = value;OnPropertyChanged(); } }
public MyCommand ShowCommand { get; set; }
public void ShowEvent()
{
Name = "Hello world";
}
}
//命令类
public class MyCommand : ICommand
{
private Action action;
public MyCommand(Action action)
{
this.action = action;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
action?.Invoke();
}
}
}
版权声明:本文为ni996570734原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。