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

13 篇文章 1 订阅

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

 

        先说下元素吧,也就是控件元素,因为代码比较简单,就不上效果了,自己可以把下面两行代码复制到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是合在一起写的,可以自行分解开看

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));
            }
        }

      
      
    }
}

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF 中,可以使用后台代码绑定数据,以下是一些常用的绑定方式: 1. 绑定到属性:可以使用 Binding 对象将控件的属性与后台数据源的属性绑定起来。例如: ``` // 假设 DataContext 是一个对象,其中有一个名为 Name 的属性 Binding binding = new Binding("Name"); binding.Source = DataContext; textBox.SetBinding(TextBox.TextProperty, binding); ``` 上面的代码将一个 TextBox 的 Text 属性与 DataContext 对象的 Name 属性绑定起来,当 DataContext 对象的 Name 属性发生变化时,TextBox 中的文本也会随之更新。 2. 绑定到集合:可以使用 Binding 对象将控件的 ItemsSource 属性与后台数据源的集合绑定起来。例如: ``` // 假设 DataContext 是一个集合,例如 List<string> Binding binding = new Binding(); binding.Source = DataContext; listBox.SetBinding(ListBox.ItemsSourceProperty, binding); ``` 上面的代码将一个 ListBox 的 ItemsSource 属性与 DataContext 对象绑定起来,当 DataContext 对象中的集合发生变化时,ListBox 中的列表也会随之更新。 3. 绑定到命令:可以使用 CommandBinding 对象将控件的命令与后台的 ICommand 对象绑定起来。例如: ``` // 假设 DataContext 是一个实现了 ICommand 接口的对象 CommandBinding binding = new CommandBinding(ApplicationCommands.Open); binding.Executed += (sender, e) => DataContext.Execute(null); this.CommandBindings.Add(binding); ``` 上面的代码将一个按钮的 Command 属性与 DataContext 对象绑定起来,当按钮被点击时,DataContext 对象的 Execute 方法会被调用。 以上是一些常用的 WPF 后台代码绑定数据的方式,您可以根据具体的需求选择适合的绑定方式。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值