1. 程式人生 > 其它 >WPF關於繫結與更新修改

WPF關於繫結與更新修改

看到一些資料與教程視訊,在這裡記錄一下,

首先 我們先做好一個公共的INotifyPropertyChanged事件,也就是通知更新

 public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;
        public void OnPropertyChanged([CallerMemberName]string propertyName = "")
        {
            PropertyChanged
?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }

再建立命令類

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(); } }

然後建立我們要ViewModel類,要引用到前面寫好的通知更新類, 把方法放在set中,也就是OnPropertyChanged()方法

public class MainViewMoel:ViewModelBase
    {
        
public MainViewMoel() { Name = "GGG"; ShowCommand = new MyCommand(Show); } public MyCommand ShowCommand { get; set; } private string name =""; public string Name { get { return name; } set { name = value;OnPropertyChanged(); } } public void Show() { Name = "1111111111"; MessageBox.Show("這是個按鈕!"); } }

最後賦值到我們的對應的頁面上

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewMoel();
        }
    }

xaml 中也要繫結對應的控制元件中

 <StackPanel >
            <TextBox Height="50" Text="{Binding Name}" x:Name="txtName" Margin="5"/>
            <Button Height="50" Command="{Binding ShowCommand}"  x:Name="Btn" Margin="5"/>
        </StackPanel>

這樣就是一個測試的繫結並通知的Demo,用於以後參考

視訊講解來源WPF專案實戰合集(2022終結版)_嗶哩嗶哩_bilibili

主要是OnPropertyChanged()方法 能夠很方便的去使用