59.Prism的按钮事件绑定和数据绑定

前置准备包括:安装Prism, DataContext=new ViewModel();,让类继承    internal class ViewModel:BindableBase

关于按钮绑定步骤

首先前台命令的绑定需要用Command

Command="{Binding MyCommand}"

然后后台事件绑定需要三个内容

  • 在类的构造函数进行初始化
            MyCommand = new DelegateCommand(ExecuteMyCommand);
  • 属性设置:
public ICommand MyCommand { get; private set; }
  • 事件定义:
     private void ExecuteMyCommand()
     {
         MessageBox.Show("按钮成功绑定");
     }

数据绑定只有一个后台操作:


        private string _textBlock1;
        public string TextBlock1
        {
            get { return _textBlock1; }
            set { SetProperty(ref _textBlock1, value); }

        }

XAML代码


    
        

C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Xml;

namespace 如何使用Prism
{
    internal class ViewModel:BindableBase
    {

        private string _textBlock1;
        public string TextBlock1
        {
            get { return _textBlock1; }
            set { SetProperty(ref _textBlock1, value); }

        }

        public ViewModel()
        {
            _textBlock1= "TextBlock1成功绑定";
            MyCommand = new DelegateCommand(ExecuteMyCommand);
        }


        public ICommand MyCommand { get; private set; }


        private void ExecuteMyCommand()
        {
            MessageBox.Show("按钮成功绑定");
        }





    }
}
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace 如何使用Prism
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext=new ViewModel();
        }
    }
}

你可能感兴趣的:(ui,c#,wpf,开发语言)