WPF 綁定表達式和綁定數(shù)據(jù)源(一)

關(guān)于綁定:[Binding]

綁定:描述的是一種關(guān)系,同構(gòu)某種關(guān)系將多個事物聯(lián)系在一起。
  •   頁面對象的屬性(必須是依賴屬性):目標 Target 
    
  •   需要顯示在界面上做交互關(guān)聯(lián)的數(shù)據(jù)對象 :源 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}" :將頁面對象的某個屬性與數(shù)據(jù)源建立聯(lián)系。
    通過綁定可以將界面與數(shù)據(jù)邏輯進行隔離。
2、綁定數(shù)據(jù)源
1、指定方式:
            Source、ElementName、DataContext、RelativeSource、Path、XPath

      2、數(shù)據(jù)源類型  

           1)依賴對象作為數(shù)據(jù)源
<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) 普通數(shù)據(jù)類型或集合類型作為數(shù)據(jù)源
<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>
            <!--普通對象,集合對象綁定   結(jié)束-->
            3) 單個對象作為數(shù)據(jù)源,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="這是單個對象作為數(shù)據(jù)源,INotifyPropertyChanged  " x:Key="dataclass"></local:DataClass>
    </Window.Resources> 
<Window>
<!--單個對象作為數(shù)據(jù)源,INotifyPropertyChanged  開始-->
<TextBlock Text="{Binding Source={StaticResource dataclass},Path=Value}"></TextBlock>
<!--單個對象作為數(shù)據(jù)源,INotifyPropertyChanged  結(jié)束-->      
</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作為數(shù)據(jù)源

新建一個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  數(shù)據(jù)綁定 開始-->    <TextBlock Text="{Binding Source={StaticResource xmlData},XPath= name}"></TextBlock>    <!--xml  數(shù)據(jù)綁定 結(jié)束--> </Window>             //第二種讀取方式   讀取對象屬性<Window.Resources>         <XmlDataProvider x:Key="xmlData" Source="pack://application:,,,/WpfApp2;component/simple.xml"> </XmlDataProvider>    </Window.Resources>            <Window>    <!--xml  數(shù)據(jù)綁定 開始-->    <TextBlock Text="{Binding Source={StaticResource xmlData},XPath= breakfast_menu/food[1]/name}"></TextBlock>    <!--xml  數(shù)據(jù)綁定 結(jié)束--> </Window>//備注:xml文件多節(jié)點下標是從1開始的。  
        5)ObjectDataProvider作為數(shù)據(jù)源

               新建類:【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) 靜態(tài)對象屬性作為數(shù)據(jù)源

                新建靜態(tài)類:[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  必須與屬性名稱一一對應(yīng)【不推薦】
        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> 
            <!--靜態(tài)對象屬性綁定--> 
            <!--單一綁定值-->
            <TextBlock Text="{Binding Path=(local:StaticClass.MyProperty)}"></TextBlock>
            <!--屬性值發(fā)生變化后通知屬性變化-->
            <TextBlock Text="{Binding Path=(local:StaticClass.Value)}"></TextBlock>
        </StackPanel>  
    </Grid>
</Window>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容