1、项目建构
2、自定义命令
namespace WpfDemo.Base
{
public class MyCommand : ICommand
{
Action executeAction;
public MyCommand(Action action)
{
executeAction = action;
}
public event EventHandler? CanExecuteChanged;
public bool CanExecute(object? parameter)
{
return true;
}
public void Execute(object? parameter)
{
executeAction();
}
}
}
3、属性改变
namespace WpfDemo.Base
{
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
4、界面
<Window x:Class="WpfDemo.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:WpfDemo"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<TextBox Height="30" Margin="5" Text="{Binding InputContent}"/>
<TextBox Height="30" Margin="5" Text="{Binding OutputContent}"/>
<Button Height="30" Width="75" Content="Button" Command="{Binding ShowCommand}"/>
</StackPanel>
</Window>
5、后台代码文章来源:https://www.toymoban.com/news/detail-678734.html
namespace WpfDemo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
}
6、ViewModel代码文章来源地址https://www.toymoban.com/news/detail-678734.html
namespace WpfDemo.ViewModels
{
public class MainViewModel:ViewModelBase
{
public MainViewModel()
{
ShowCommand = new MyCommand(Show);
}
private string? inputContent;
public string? InputContent
{
get { return inputContent; }
set { inputContent = value; OnPropertyChanged(); }
}
private string? outputContent;
public string? OutputContent
{
get { return outputContent; }
set { outputContent = value; OnPropertyChanged(); }
}
public MyCommand ShowCommand { get; set; }
public void Show()
{
OutputContent = InputContent;
MessageBox.Show("It is blue sky!");
}
}
}
到了这里,关于WPF自定义命令及属性改变处理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!