Binding

1新建wpf程序

2 新建Student类

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp9
{
    public class Student:INotifyPropertyChanged
    {
        private string _Name = "";
        public string Name
        {
            get { return _Name; }

            set
            {
                _Name = value;
                OnPropertyChanged("Name");
            }

        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

 3.修改ui

<Window x:Class="WpfApp9.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:WpfApp9"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <TextBox x:Name="textBoxName" Margin="5" BorderBrush="Black"/>
            <Button Content="Modify Name" Margin="5" Click="Button_Click"></Button>
        </StackPanel>
    </Grid>
</Window>

4 主程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 WpfApp9
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        Student student;
        public MainWindow()
        {
            InitializeComponent();

            student = new Student();

            //Binding binding = new Binding();
            //binding.Source = student;
            //binding.Path = new PropertyPath("Name");

            //BindingOperations.SetBinding(this.textBoxName, TextBox.TextProperty, binding);

            //可以简写成下面的样子
            this.textBoxName.SetBinding(TextBox.TextProperty,new Binding("Name"){ Source=student});
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            student.Name += "Name";
        }
    }
}

 

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读