当前位置:网站首页>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>
边栏推荐
- Kotlin common standard functions
- An auxiliary MVP architecture project quick development library -mvpfastdagger
- PMP考试多少分算通过?
- Guiding principle - read source code
- Experience in writing C
- Solution to the problem of repeated startup of esp8266
- Puzzle (019.2) hexagonal lock
- What are the PMP scores?
- Cocopod error failed: undefined method `map 'for nil:nilclass
- [MySQL learning notes 22] index
猜你喜欢

Simple waterfall effect
![[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate](/img/75/a06e20b4394579cbd9f6d3a075907a.jpg)
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate

Fcpx quickly add subtitles | Final Cut Pro import fcpxml subtitle file does not match the video time? I got it in code

Nano data World Cup data interface, CSL data, sports data score, world cup schedule API, real-time data interface of football match

Title B of the certification cup of the pistar cluster in the Ibagu catalog
![[buuctf.reverse] 117-120](/img/6c/8a90fff2bd46f1494a9bd9c77eeafc.png)
[buuctf.reverse] 117-120

Data-driven anomaly detection and early warning of item C in the May 1st mathematical modeling competition in 2021

manhattan_ Slam environment configuration

x86电脑上下载debian的arm64的包

Creo makes a mobius belt in the simplest way
随机推荐
处理图片类库
clang frontend command failed with exit code 250
Simple waterfall effect
How to make a self-made installer and package the program to generate an installer
Data-driven anomaly detection and early warning of item C in the May 1st mathematical modeling competition in 2021
The problem of wirengpi program running permission
CyCa children's physical etiquette Yueqing City training results assessment successfully concluded
(forwarding articles) after skipping multiple pages, shuttle returns to the first page and passes parameters
How to "transform" small and micro businesses (I)?
51 SCM time stamp correlation function
The way that flutter makes the keyboard disappear (forwarding from the dependent window)
Computational Thinking and economic thinking
22 mathematical modeling contest 22 contest C
CyCa 2022 children's physical etiquette primary teacher class Shenzhen headquarters station successfully concluded
2台三菱PLC走BCNetTCP协议,能否实现网口无线通讯?
x86电脑上下载debian的arm64的包
【mysql学习笔记21】存储引擎
Experience in writing C
pmp考试题型需要注意哪些?
[zero foundation understanding innovation and entrepreneurship competition] overall cognition and introduction of mass entrepreneurship and innovation competition (including FAQs and integration of bl