2021-11-30 WPF的MVVM绑定

主页面代码

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

页面设计

<TextBox x:Name="First" Width="80" Height="20" Text="{Binding Value}" Foreground="{Binding BorderColor}"></TextBox>
        <Button x:Name="Second" 
                Width="100" 
                Height="30" 
                HorizontalAlignment="Left" 
                Margin="80,0" 
                Content="按钮"
                Command="{Binding ValueCommand}"//通过这个绑定按钮命令
                CommandParameter="123"//传递按钮参数
                ></Button>

定义Command

public class CommandBase : ICommand
    {
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            DoAction?.Invoke(parameter);//命令传递到这个委托
        }
        public Action<object> DoAction { get; set; }
    }

ViewModel页面定义

public class MainViewModel:INotifyPropertyChanged
    {  
        private string _value="200";
        public string Value
        {
            get { return _value; }
            set { 
                _value = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));//响应式
            }
        }


        private Brush _borderColor=Brushes.Red;

        public event PropertyChangedEventHandler PropertyChanged;//参数变化事件

        public Brush BorderColor
        {
            get { return _borderColor; }
            set { _borderColor = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ValueColor"));
            }
        }

        private ICommand _valueCommand;

        public ICommand ValueCommand
        {
            get {
                if (_valueCommand==null)
                {
                    _valueCommand = new CommandBase() { DoAction = new Action<object>(ValueCommandAction) };//命令执行的方法
                }
                return _valueCommand; }
            set { _valueCommand = value; }
        }
        private void ValueCommandAction(object obj)
        {
            Value = "299";
        }
    }

 

posted @ 2021-11-30 09:50  月长生  阅读(211)  评论(0)    收藏  举报