WPF数据绑定

WPF中的数据绑定是一个强大的机制,它允许将用户界面(UI)元素与后端数据源动态连接。这种连接方式使得UI元素的显示值与数据源的值保持同步,当数据源的值发生变化时,UI元素会自动更新,反之亦然。

数据绑定的类型

ElementName依据Name相互绑定的
RelativeSource相对于本身或者父元素
ltemSouce绑定到集合元素
DataContext多种不同值绑定

ElementName实例:

将textbox的文本内容绑定到button上(当textbox文本发生变化时,button内容也会跟着变化)
ElementName :  确定绑定的元素
path : 绑定的属性

<StackPanel Orientation="Vertical">
    <TextBox Height="30"
             Width="100"
             BorderBrush="Black" Name="t"></TextBox>
    <Button Width="100"
            Height="40"
            Content="{Binding ElementName=t,Path=Text}"></Button>
</StackPanel>

RelativeSource实例:

属性介绍 :

Mode : 设置绑定的元素是本身还是父元素 (值 :  Self本身  FindAncestor祖先)

AncestorType: 设置绑定父元素的类型

Path: 绑定的属性

<StackPanel Margin="0,100,0,0">
    <Button Height="40"
            FontSize="15"
            Content="{Binding RelativeSource={RelativeSource Mode=Self},Path=Height}" />
    <Button Height="40"
            FontSize="15"
            Content="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=StackPanel},Path=Margin}" />
</StackPanel>

ltemSouce实例:

第一步: 设置标签

<ListBox Name="l3"
         Width="200"
         Height="100"
         ItemsSource="{Binding}">
</ListBox>

第二步: 设置数据并且进行绑定

ObservableCollection:表示一个动态数据收集,该集合在添加或删除项或刷新整个列表时提供通知。

ObservableCollection<string> list = new ObservableCollection<string>();
list.Add("李四");
list.Add("张三");
list.Add("王五");
this.l3.DataContext = list;

DataContext实例:

INotifyPropertyChanged :是一个接口,它用于在属性值发生更改时通知 WPF UI 元素。当一个类实现了 INotifyPropertyChanged 接口,并且在属性值发生更改时触发 PropertyChanged 事件时,WPF 可以自动更新绑定到这些属性的 UI 元素。

第一步:设置标签

<Grid Name="g"
      DataContext="{Binding}">
    <Button Width="100" Height="40" Content="{Binding Path=One}" ></Button>
    <Button Width="100" Height="40" Content="{Binding Path=Two}"></Button>
</Grid>

第二步:创建模型类 并且进行数据绑定

//创建数据模型类并添加INotifyPropertyChanged接口
public class A : INotifyPropertyChanged
{
    public string One { get; set; }
    public string Two { get; set; }
    // 实现INotifyPropertyChanged这个接口的PropertyChanged属性
    // PropertyChanged类型是委托函数
    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        // 当属性修改的时候触发PropertyChanged事件,紧跟着调用该函数
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

// 在cs中整理数据并且绑定
this.g.DataContext = new A(){One = "我是One", Two = "我是two" };

  • 13
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值