WPF MVVM 简单实现

public class DelegateCommands:ICommand
    {
        public bool CanExecute(object parameter)
        {
            if (CanExecuteHander == null)
                return true;
            return CanExecuteHander(parameter);
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (ExecuteHander == null)
                return;
            ExecuteHander(parameter);
        }

        public Func<object, bool> CanExecuteHander;

        public Action<object> ExecuteHander;
    }



/// <summary>
    /// 通知属性
    /// </summary>
    public class NotifyPropertyChanged:INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void RasePropertyChange(string propertyName)
        {
            if (PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

public class AddViewModel:NotifyPropertyChanged
    {
        private int input1;
        public int Input1
        {
            get { return this.input1; }
            set
            {
                this.input1 = value;
                this.RasePropertyChange("Input1");
            }
        }

        private int input2;
        public int Input2
        {
            get { return this.input2; }
            set
            {
                this.input2 = value;
                this.RasePropertyChange("Input2");
            }
        }

        private int result;
        public int Result
        {
            get { return this.result; }
            set
            {
                this.result = value;
                this.RasePropertyChange("Result");
            }
        }

        public DelegateCommands Add { get; set; }

        public void AddResult(object parameter)
        {
            this.Result = this.Input1 + this.Input2;
        }

        public AddViewModel()
        {
            this.Add = new DelegateCommands();
            Add.ExecuteHander += new Action<object>(AddResult);
        }
    }

<StackPanel Orientation="Horizontal" Margin="20">
        <TextBox Text="{Binding Input1}" ></TextBox>
        <TextBox Text="{Binding Input2}"></TextBox>
        <TextBox Text="{Binding Result}"></TextBox>
        <Button Command="{Binding Add}">加</Button>
    </StackPanel>

 public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new AddViewModel();
        }

  注:在xaml文件中绑定数据以及命令的数据源,WPF默认情况下会使用冒泡的方式找DataContent的对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拥有必珍惜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值