WPF之绑定!

文章目录


前言

WPF之绑定!


一、绑定基础

绑定源:通常是一个数据对象,例如类实例、集合或 XML 数据。

绑定目标:一般是一个 UI 元素的属性。
数据绑定的核心元素

Binding 对象:描述了源属性和目标属性之间的连接。

Binding Target:通常是一个 DependencyProperty(依赖属性)。

Binding Source:可以是任意对象。

DataContext:数据上下文,通常用于为整个控件树提供绑定源的默认数据源。

数据转换:在源和目标之间转换数据,例如格式化显示数据。

二、使用

1.XML元素之间的绑定

XML元素之间的绑定

c 复制代码
<TextBox Text="{Binding ElementName=slider, Path=Value}" Margin="5" Height="30"/>

Text属性通过数据绑定(Binding)连接到Slider的Value属性。

ElementName=slider: 绑定源是名为slider的控件。

Path=Value: 绑定到Slider的Value属性(即滑块当前值)。绑定到那个属性

​​效果​​:当拖动滑块时,这个文本框会实时显示滑块当前值(双向绑定默认,所以如果用户在文本框中输入有效数值,滑块也会相应移动)。

c 复制代码
<Grid>
    <StackPanel>
        <Slider x:Name="slider" Margin="5"/>
        <TextBox Text="{Binding ElementName=slider,Path=Value}"    Margin="5" Height="30"/>
        <TextBox  Margin="5" Height="30"/>
        <TextBox  Margin="5" Height="30"/>
    </StackPanel>
</Grid>

2.绑定模式

绑定模式分类表

绑定模式 数据流向 默认适用控件 应用场景 性能特点
OneWay 源 → 目标 TextBlock, Label, ProgressBar 数据显示、计算结果展示 中等
TwoWay 源 ↔ 目标 TextBox, Slider, CheckBox 表单输入、用户配置设置 较高
OneTime 仅初始时 所有显示控件 静态数据、初始化配置 最低
OneWayToSource 目标 → 源 Slider, ScrollBar 用户输入收集、无初始值绑定 中等
Default 自动决定 - 通用场景 自动优化
c 复制代码
<Grid>
    <StackPanel>
        <Slider x:Name="slider" Margin="5"/>
        <!-- 只显示第一次的数据源的值 -->
        <TextBox Text="{Binding ElementName=slider,Path=Value, Mode=OneTime}"    Margin="5" Height="30"/>
        <!-- 单向绑定 数据源到目标 -->
        <TextBox Text="{Binding ElementName=slider,Path=Value,Mode=OneWay}"  Margin="5" Height="30"/>
        <!-- 单向绑定 目标到数据源 -->
        <TextBox Text="{Binding ElementName=slider,Path=Value, Mode=OneWayToSource}"  Margin="5" Height="30"/>
        <!-- 双向绑定 目标到数据源 数据源到目标 -->
        <TextBox Text="{Binding ElementName=slider,Path=Value, Mode=TwoWay}"  Margin="5" Height="30"/>
        <!-- 与双向绑定一样 -->
        <TextBox Text="{Binding ElementName=slider,Path=Value, Mode=Default}"  Margin="5" Height="30"/>
    </StackPanel>
</Grid>

效果图

3.使用ListBox绑定

c 复制代码
public class ViewAViewModel:BindableBase
{
    // 字符串集合属性
    private ObservableCollection<string> _items;
    public ObservableCollection<string> Items
    {
        get => _items;
        set => SetProperty(ref _items, value);
    }

    // 自定义对象集合属性
    private ObservableCollection<Person> _persons;
    public ObservableCollection<Person> Persons
    {
        get => _persons;
        set => SetProperty(ref _persons, value);
    }

    // 构造函数
    public ViewAViewModel()
    {
        // 初始化字符串集合
        Items = new ObservableCollection<string>
        {
            "项目 1",
            "项目 2",
            "项目 3"
        };

        // 初始化自定义对象集合
        Persons = new ObservableCollection<Person>
    {
        new Person { Id = 1, Name = "张三", Age = 30 },
        new Person { Id = 2, Name = "李四", Age = 25 },
        new Person { Id = 3, Name = "王五", Age = 28 }
    };
    }
}
// 自定义模型类
public class Person : BindableBase
{
    private int _id;
    public int Id
    {
        get => _id;
        set => SetProperty(ref _id, value);
    }

    private string _name;
    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }

    private int _age;
    public int Age
    {
        get => _age;
        set => SetProperty(ref _age, value);
    }
}
c 复制代码
    </Grid>
    <!-- 定义资源 -->
    <UserControl.Resources>
        <!-- 自定义数据显示模板 -->
        <DataTemplate DataType="{x:Type local:Person}">
            <StackPanel Orientation="Horizontal" Margin="5">
                <TextBlock Text="{Binding Id}" Width="30"/>
                <TextBlock Text="{Binding Name}" Width="100" FontWeight="Bold"/>
                <TextBlock Text="{Binding Age}" Width="50"/>
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>
```
---
效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/b3040a3c38e04ab18102e7690448e042.png)
相关推荐
hez20103 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
雨落倾城夏未凉8 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫9 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫10 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m62510 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户917215619021110 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠11 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫13 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech13 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf15 天前
C#摸鱼实录——IoC与DI案例详解
c#