关于绑定:[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>