WPF7-数据绑定基础

发布于:2025-02-18 ⋅ 阅读:(143) ⋅ 点赞:(0)

1. WPF数据绑定试验

以下是一个简单的 WPF 数据绑定示例,使用两个TextBox控件分别表示Name和Age来进行进行数据绑定试验。

数据模型类

创建一个 Person 类,包含 NameAge 属性,并实现 INotifyPropertyChanged 接口以支持数据绑定。


namespace WpfApp1

{

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Person person;
        public MainWindow()
        {
            InitializeComponent();


            person = new Person { Name = "张三", Age = 25 };
            DataContext = person;
        }


        private void Button_Click_Update_Person(object sender, RoutedEventArgs e)
        {
            // 更新 Person 对象的属性值
            person.Name = "李四";
            person.Age = 30;
        }


        private void Button_Click_Submit_Person(object sender, RoutedEventArgs e)
        { 
            MessageBox.Show(string.Format("当前姓名为:{0},年龄为:{1}", person.Name, person.Age));
        }
    }


    public class Person : INotifyPropertyChanged
    {
        private string name;
        private int age;


        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                OnPropertyChanged(nameof(Name));
            }
        }


        public int Age
        {
            get { return age; }
            set
            {
                age = value;
                OnPropertyChanged(nameof(Age));
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;


        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}



XAML 界面

在 XAML 中创建一个简单的界面,包含一个 TextBox 用于输入名字,一个 TextBox 用于显示年龄。

两个button按钮,一个修改后台person对象,一个获取页面上输入的值。


<Window x:Class="WpfApp1.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF 数据绑定" Height="450" Width="800">
    <Grid Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>


        <!-- 名字输入框 -->
        <Grid Grid.Row="0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Label Content="名字:" Grid.Column="0" />
            <TextBox Grid.Column="1" Text="{Binding Name}" />
        </Grid>


        <!-- 年龄显示 -->
        <Grid Grid.Row="1" Margin="0,10,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Label Content="年龄:" Grid.Column="0" />
            <TextBox Grid.Column="1" Text="{Binding Age}" />
        </Grid>
        
        <Grid Grid.Row="2" Margin="0,10,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="100" />
                <ColumnDefinition Width="100" />
            </Grid.ColumnDefinitions>
            <Button Content="修改后台person" Click="Button_Click_Update_Person" Grid.Column="0"/>
            <Button Content="提交界面person" Click="Button_Click_Submit_Person" Grid.Column="1"/>
        </Grid>
    </Grid>
</Window>



运行效果:

文章配图

运行程序后,你会看到初始界面中TextBox 中显示初始名字 “张三”,TextBox 中显示初始年龄 “25”。

当你在 TextBox 中修改名字时,Person 对象的 Name 属性会被自动更新,反之亦然。

这是因为 TextBox 和 Person 对象之间建立了双向数据绑定。

1.1. 数据绑定的核心实现

INotifyPropertyChanged 接口:Person 类实现了该接口,当属性值发生变化时,会通知绑定的控件更新。

1.2. {Binding}语法

在 XAML 中使用 {Binding Name}{Binding Age} 将控件绑定到 Person 对象的属性。

1.3. 理解 DataContext

DataContext:通过设置DataContext = person,将 Person 对象设置为窗口的数据上下文,使控件能够访问 Person 对象的属性。

在 WPF中,DataContext 是一个非常重要的概念,它用于定义数据绑定的上下文环境。

当你看到 DataContext = person; 这句代码时,它实际上是在为当前的 UI 元素(如窗口、控件等)设置数据绑定的源对象。

DataContext 是一个依赖属性,存在于 FrameworkElement 类中,因此所有继承自 FrameworkElement 的控件(如 Window、UserControl、TextBox、Button 等)都可以设置 DataContext。它的主要作用是为控件及其子控件提供一个默认的数据源,用于数据绑定。

通过这个简单示例,你可以快速掌握WPF数据绑定的基本原理和实现方法。


网站公告

今日签到

点亮在社区的每一天
去签到