当前位置:网站首页>WPF 绑定表达式和绑定数据源(一)
WPF 绑定表达式和绑定数据源(一)
2022-06-25 09:38:00 【@@Mr.Fu】
关于绑定:[Binding]
绑定:描述的是一种关系,同构某种关系将多个事物联系在一起。
页面对象的属性(必须是依赖属性):目标 Target
需要显示在界面上做交互关联的数据对象 :源 Source
<Window x:Class="WpfApp2.BindingDemo.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp2.BindingDemo" mc:Ignorable="d" Title="Window1" Height="450" Width="800"> <Grid> <TextBlock Text="{Binding Source=data,Path=value}"></TextBlock> </Grid> </Window> //备注: //Text:目标 //Source=data,Path=value 源: 也是绑定表达式
1、绑定表达式
Text="{Binding Source=data,Path=value}" :将页面对象的某个属性与数据源建立联系。
通过绑定可以将界面与数据逻辑进行隔离。
2、绑定数据源
1、指定方式:
Source、ElementName、DataContext、RelativeSource、Path、XPath
2、数据源类型
1)依赖对象作为数据源
<Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" Name="window">
<Grid>
<StackPanel>
<!--依赖对象绑定-->
<TextBox Name="txt" Text="123"></TextBox>
<TextBlock Text="{Binding ElementName= txt,Path=Text}"></TextBlock>
<TextBlock Text="{Binding ElementName= window,Path=Title}"></TextBlock>
<TextBlock Text="Solider当前值:"></TextBlock>
<TextBlock Text="{Binding ElementName=slider,Path= Value}"></TextBlock>
<Slider Width="200" Name="slider" Minimum="5" Maximum="100" HorizontalAlignment="Left"></Slider>
<TextBlock Text="Solider最小值:"></TextBlock>
<TextBlock Text="{Binding ElementName=slider,Path=Minimum}"></TextBlock>
</StackPanel>
</Grid>
</Window>
2) 普通数据类型或集合类型作为数据源
<Window.Resources>
<sys:String x:Key="name">小明</sys:String>
<x:Array x:Key="data" Type="sys:String">
<sys:String>小刚</sys:String>
</x:Array>
</Window.Resources>
<!--普通对象,集合对象绑定 开始-->
<TextBlock Text="{Binding Source={StaticResource name}}"></TextBlock>
<TextBlock Text="{Binding Source={StaticResource data},Path=[0]}"></TextBlock>
<!--普通对象,集合对象绑定 结束-->
3) 单个对象作为数据源,INotifyPropertyChanged
新建类:DataClass 继承 INotifyPropertyChanged
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp2
{
public class DataClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private string _Value;
public string Value
{
get { return _Value; }
set
{
_Value = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
}
}
}
}
xaml代码:
<Window.Resources>
<local:DataClass Value="这是单个对象作为数据源,INotifyPropertyChanged " x:Key="dataclass"></local:DataClass>
</Window.Resources>
<Window>
<!--单个对象作为数据源,INotifyPropertyChanged 开始-->
<TextBlock Text="{Binding Source={StaticResource dataclass},Path=Value}"></TextBlock>
<!--单个对象作为数据源,INotifyPropertyChanged 结束-->
</Window>
xaml.cs 代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 WpfApp2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Task.Run(() => {
Task.Delay(2000).GetAwaiter().GetResult();
this.Dispatcher.Invoke(() => {
(this.Resources["dataclass"] as DataClass).Value = "";
});
});
}
}
}
4)XmlDataProvider作为数据源
新建一个XML文件:【simple.xml】
<?xml version="1.0" encoding="iso-8859-1"?>
<breakfast_menu>
<food attr="a1" prop="p1">
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food attr="a2">
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
<food attr="a3">
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
<calories>900</calories>
</food>
<food attr="a4">
<name>French Toast</name>
<price>$4.50</price>
<description>thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>
<food attr="a5">
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
<calories>950</calories>
</food>
</breakfast_menu>
xaml 代码如下:
//d第一种读取方式 读取对象属性<Window.Resources> <XmlDataProvider x:Key="xmlData" Source="pack://application:,,,/WpfApp2;component/simple.xml" XPath="breakfast_menu/food[1]"> </XmlDataProvider> </Window.Resources> <Window> <!--xml 数据绑定 开始--> <TextBlock Text="{Binding Source={StaticResource xmlData},XPath= name}"></TextBlock> <!--xml 数据绑定 结束--> </Window> //第二种读取方式 读取对象属性<Window.Resources> <XmlDataProvider x:Key="xmlData" Source="pack://application:,,,/WpfApp2;component/simple.xml"> </XmlDataProvider> </Window.Resources> <Window> <!--xml 数据绑定 开始--> <TextBlock Text="{Binding Source={StaticResource xmlData},XPath= breakfast_menu/food[1]/name}"></TextBlock> <!--xml 数据绑定 结束--> </Window>//备注:xml文件多节点下标是从1开始的。
5)ObjectDataProvider作为数据源
新建类:【MethodClass】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp2
{
public class MothedClass
{
public double GetValue(string value)
{
return double.Parse(value) * 0.5;
}
}
}
xmal 代码如下:
<Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
xmlns:sys="clr-namespace:System;assembly=System.Runtime"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<ObjectDataProvider ObjectType="{x:Type local:MothedClass}" x:Key="dataobject" MethodName="GetValue">
<ObjectDataProvider.MethodParameters>
<sys:String>
200
</sys:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<Border BorderBrush="Black" BorderThickness="1" Height="{Binding Source={StaticResource dataobject}}" Width="{Binding Source={StaticResource dataobject}}">
<TextBlock Text="{Binding Source={StaticResource dataobject}}"></TextBlock>
</Border>
</Grid>
</Window>
6) 静态对象属性作为数据源
新建静态类:[StaticClass]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfApp2
{
public class StaticClass
{
public static int MyProperty { get; set; } = 555;
//通知 第一种方式 [Value]Changed 必须与属性名称一一对应【不推荐】
public static event EventHandler<PropertyChangedEventArgs> ValueChanged;
//通知 第二种方式
public static event EventHandler<PropertyChangedEventArgs> StaricPropertyChanged;
private static int value { get; set; }=66;
public static int Value
{
get { return value; }
set { Value = value;
//通知 第一种方式 【不推荐】
// ValueChanged?.Invoke(null,new PropertyChangedEventArgs("Value"));
//通知 第二种方式
StaricPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("Value"));
}
}
}
}
xaml:代码如下
<Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
xmlns:sys="clr-namespace:System;assembly=System.Runtime"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" Name="window">
<Grid>
<StackPanel>
<!--静态对象属性绑定-->
<!--单一绑定值-->
<TextBlock Text="{Binding Path=(local:StaticClass.MyProperty)}"></TextBlock>
<!--属性值发生变化后通知属性变化-->
<TextBlock Text="{Binding Path=(local:StaticClass.Value)}"></TextBlock>
</StackPanel>
</Grid>
</Window>
边栏推荐
- How much money have I made by sticking to fixed investment for 3 years?
- Android database security: after the user exits, the transaction rollback log still stores relevant data information
- Notes on writing questions in C language -- monkeys eat peaches
- Learning notes of rxjs takeuntil operator
- PHP obtains the IP address, and the apache2 server runs without error
- 2021mathorcupc topic optimal design of heat dissipation for submarine data center
- Download the arm64 package of Debian on X86 computer
- Pytorch_Geometric(PyG)使用DataLoader报错RuntimeError: Sizes of tensors must match except in dimension 0.
- Kotlin advanced set
- Remittance international empowers cross-border e-commerce: to be a compliant cross-border payment platform!
猜你喜欢
Can two Mitsubishi PLC adopt bcnettcp protocol to realize wireless communication of network interface?
Rxjs TakeUntil 操作符的学习笔记
x86电脑上下载debian的arm64的包
Methodchannel of flutter
Wallys/MULTI-FUNCTION IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL
Applet cloud development joint table data query and application in cloud function
I put a two-dimensional code with rainbow candy
Download the arm64 package of Debian on X86 computer
Data-driven anomaly detection and early warning of 21 May Day C
2台三菱PLC走BCNetTCP协议,能否实现网口无线通讯?
随机推荐
8. Intelligent transportation project (1)
[MySQL learning notes 20] MySQL architecture
8、智慧交通项目(1)
Solution to the problem of repeated startup of esp8266
MongoDB的原理、基本使用、集群和分片集群
在指南针上面开股票账户好不好,安不安全?
Can two Mitsubishi PLC adopt bcnettcp protocol to realize wireless communication of network interface?
Match a mobile number from a large number of mobile numbers
从海量手机号中匹配某一个手机号
Arduino bootloader burning summary
Modbus协议与SerialPort端口读写
Redis(一)原理与基本使用
Nano data World Cup data interface, CSL data, sports data score, world cup schedule API, real-time data interface of football match
Etcd教程 — 第四章 Etcd集群安全配置
[smart agriculture program] smart agriculture small program project is currently popular.
Processing picture class library
Why should the terminal retail industry choose the member management system
I put a two-dimensional code with rainbow candy
The gradle configuration supports the upgrade of 64 bit architecture of Xiaomi, oppo, vivo and other app stores
What should be paid attention to in PMP examination?