wpf数据绑定之元素、资源、后台绑定

这篇具有很好参考价值的文章主要介绍了wpf数据绑定之元素、资源、后台绑定。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

        wpf前端的数据绑定主要分为元素、资源以及后台数据三种,元素可以简单的理解为前端的空间数据绑定,资源是在resource里找数据,而后台就是跟cs文件之间的数据互相传递。

wpf数据绑定之元素、资源、后台绑定

 

        先说下元素吧,也就是控件元素,因为代码比较简单,就不上效果了,自己可以把下面两行代码复制到xaml文件里运行看,主要就是一个滑动块与文本框互相影响的效果,如果用winfrom来实现,要为两个控件分别写个方法。

        <Slider Name="sd"  Width="200"   />
        <TextBox Text="{Binding ElementName=sd,Path=Value}"  Height="40"   Width="200"/>

        接着说资源数据绑定,用到了resource,可以自己设置数据源到xml文件里,然后前端用key名称来获取值
       

<Window.Resources >
        <TextBlock x:Key="txt">hello world</TextBlock>

</Window.Resources>

  <!--资源绑定-->
        <TextBox Text="{Binding  Source={StaticResource  txt}, Path=Text}" TextWrapping="Wrap/>

        最后,来讲下重点后台数据绑定,也是wpf精华的地方,后台数据绑定可以把数据绑定到窗口,也可以绑定到控件。

1、先展示一下绑定到控件的写法,先在xaml里写入

<TextBlock x:Name="txt2" Text="{Binding Name,FallbackValue=没找到 }" HorizontalAlignment="Left" Margin="52,140,0,0" TextWrapping="Wrap"  Width="100" VerticalAlignment="Top" />

然后在cs文件里写入,这样程序运行后,自动就会在文本框里显示李四的字样了。
   

    //student st = new student() { Name = "张三1" };
    //txt2.DataContext = st;  

    txt2.DataContext = new student() 


  class student 
    {
        public string Name { get  ; set  ; } ="李四";
    }

2、接着展示一下绑定到窗口的写法,先增加一个类,叫MainViewModel.cs,内容如下:

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

namespace WpfApp7
{
    class MainViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        private int age;
        public int Age
        {
            get {return  age; }
            set
            {
                age = value;
                NotifyPropertyChanged("Age");
            }
        }
        public int Height { get => height; set => height = value; }
        int height;
        public MainViewModel()
        {
            Age = 18;
            Height = 171;
        }

    }
}

在mianwindow窗口里,通过实例化的方法把值获取到,代码如下:

  this.DataContext =new  MainViewModel();



 private void Button_Click(object sender, RoutedEventArgs e)
        {
            MainViewModel mvd = (MainViewModel)this. DataContext;
            mvd.Age++;//Age会增加,因为有  NotifyPropertyChanged("Age");
            mvd.Height++;//Height不会增加
        }

最后在xaml里展示出来

        <TextBox   Text="{Binding Age}" VerticalAlignment="Top" Width="120"/>

3、绑定到后台数据,先上xaml部分

<DataGrid ItemsSource="{Binding StuCln}" HorizontalAlignment="Left" Height="143" Margin="365,28,0,0" VerticalAlignment="Top" Width="400">
            <DataGrid.Columns  >
                <DataGridTextColumn Header="序号" Binding="{Binding Id}"></DataGridTextColumn>
                <DataGridTextColumn Header="姓名" Binding="{Binding Name}"></DataGridTextColumn>
                <DataGridTextColumn Header="年龄" Binding="{Binding Age}"></DataGridTextColumn>
            </DataGrid.Columns>

接着是代码部分,这里有个mvvm的思想,就是model类和viewmodel类要区分开,本demo是合在一起写的,可以自行分解开看文章来源地址https://www.toymoban.com/news/detail-445273.html

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
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 WpfApp9
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        Student stu;
        

        public MainWindow()
        {
            InitializeComponent();
            stu = new Student() { Id = 1, Name = "张三", Age = 18 }; //初始化数据
            stu.StuCln = new ObservableCollection<Student>();

            stu.StuCln.Add(stu);
            this.DataContext = stu;
        }

       
        


 



    }




   public  class Student : INotifyPropertyChanged
    {
        //旧的写法,标准但是繁琐
        private int id;
        public int Id
        {
            get { return id; }
            set
            {
                id = value;
                NotifyPropertyChanged("Id");
            }
        }
        // 简化后错误写法,无法生效
        private string name;
        public string Name
        {
            get => name; 
            set => setValue(ref name, value,Name);//这种写法值不会变
        }

        //简化后正确写法
        private int age;
        public int Age 
        {     
            get => age;
            set => setValue(ref age, value,nameof(Age));
        }
        private void setValue<T>(  ref T propertyName, T  value,string   fatherPropertyName)
        {
            propertyName = value;
            NotifyPropertyChanged(fatherPropertyName);
        }

        ObservableCollection<Student> stuCln;
        public ObservableCollection<Student> StuCln
        { 
            get => stuCln;
            set => setValue(ref stuCln, value, nameof(StuCln));
        }


        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

      
      
    }
}

到了这里,关于wpf数据绑定之元素、资源、后台绑定的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C# WPF 数据绑定

    后台变量发生改变,前端对应的相关属性值也发生改变 接口 INotifyPropertyChanged 用于通知客户端(通常绑定客户端)属性值已更改。 官方示例代码如下 示例演示 before after 本示例提供了多种绑定方式,使用接口进行绑定,不使用接口进行绑定 1.在MainWindow中进行属性更改 2.在

    2024年02月02日
    浏览(32)
  • WPF 入门笔记 - 04 - 数据绑定

    慢慢来,谁还没有一个努力的过程。 --网易云音乐 数据绑定概述 (WPF .NET) 什么是数据绑定? 数据绑定(Data Binding)是 WPF 一种强大的机制,用于在应用程序的各个部分之间建立数据的双向关联。它允许你将数据从一个源(例如对象、集合、数据库等)绑定到目标控件的属性,

    2024年02月09日
    浏览(48)
  • WPF 数据绑定类属性 和数据更新

    WPF中数据绑定是一个非常强大的功能,不仅可以绑定后台数据,还可以进行实时更新。 在后台创建模型类,然后在标签页面进行导入并绑定。 // 实现数据更新需要再模型类里面添加INotifyPropertyChanged接口 // INotifyPropertyChanged 检查属性是否发生变化的接口 此方法在模型类数据变

    2024年04月15日
    浏览(24)
  • 记一次WPF的DataGrid绑定数据

    之前一直在用winform,但是感觉界面不好看,然后就自己在网上学习WPF。一开始看到DataGrid的时候,还以为它是DataGridView,然后用winform的方法绑定数据发现不行,在不断的查找之后,终于学会了怎么简单的绑定数据。 工具:VStudio2022 框架:.net framework 4.8 新建一个 WPF 窗体,再

    2024年03月28日
    浏览(35)
  • WPF绑定(Binding)下的数据验证IDataErrorInfo

    WPF中Binding数据校验、并捕获异常信息的三种方式讲到了三种方式,其中使用ValidatinRule的方式比较推荐,但是如果一个类中有多个属性,要为每个属性都要声明一个ValidatinRule,这样做非常麻烦。可以让类继承自 IDataErrorInfo 来解决这个问题。 IDataErrorInfo基本使用 Data类中具有多

    2023年04月15日
    浏览(27)
  • WPF实战学习笔记29-登录数据绑定,编写登录服务

    添加登录绑定字段、命令、方法 修改对象:Mytodo.ViewModels.ViewModels 添加密码依赖对象行为 添加文件:Mytodo.Extensions.PassWordExtensions ### 登录UI添加密码行为 修改文件:Mytodo.Views.LoginView.xmal 添加命名空间,略 修改passbox。 添加加密方法,并使用 添加文件:MyToDo.Share.StringE

    2024年02月15日
    浏览(26)
  • WPF 零基础入门笔记(3):数据绑定详解(更新中)

    WPF基础知识博客专栏 WPF微软文档 WPF控件文档 B站对应WPF数据绑定视频教程 我们在之前的文章中,详细解释了数据模版和控件模板。简单来说数据模板和控件模板就是为了解决代码重复的问题。我们可以回顾一下之前的所有内容。 为了不写重复的样式,WPF提供了样式设置 为了

    2024年02月11日
    浏览(27)
  • 微信小程序-绑定数据并在后台获取它

    如图 遍历列表的过程中需要绑定数据,点击时候需要绑定数据 这里是源代码 这里有几个点注意: 1、代码别写到最外层的view上了,传不到这个button上 data-product-id=“{{item.productId}}” XXXXX 2、如何点击按钮获取当前的 商品id和上下架状态呢? catchtap=“onShelf” 或者 bindtap=“on

    2024年02月21日
    浏览(29)
  • 解决WPF绑定数据源,数据更新,UI不更新的问题

    XAML中已经设置 View中已经实现IDisposable接口。 ViewModel中已经实现INotifyPropertyChanged接口方法RaisePropertyChanged。 Model中已经配置TextValue 如果已经正确设置Model与ViewModel的 INotifyPropertyChanged ,且Model中的数据可以执行 RaisePropertyChanged ,但此时UI仍不能更新,请检查View中是否 DataCont

    2024年02月14日
    浏览(28)
  • WPF 解决 Style.Trigger 中数据绑定失效的问题

    参考:stackoverflow 有如下代码,发现在 ImageSource=\\\"{Binding SomeImage}\\\" 中没有绑定的当前的 DataContext 改成如下即可

    2024年02月11日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包