WPF-数据绑定

下面记录了几种数据绑定时的场景,以供之后自己参考。

一、Path=.的Binding

这是数据绑定中的特殊情况,Binding源本身就数据且不需要Path来指明,string、int等基本数据。

<Window x:Class="WpfApplication1.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:WpfApplication1"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="250" Width="359">
    <StackPanel Margin="0,0,0,0">
        <StackPanel.Resources>
            <sys:String x:Key="myString">
                学习WPF
            </sys:String>
        </StackPanel.Resources>
        <TextBlock Name="textBlock1" Text="{Binding Path=.,Source={StaticResource ResourceKey=myString}}">
        </TextBlock>
    </StackPanel>
</Window>

等效成C#代码

string myString = “学习WPF”;
this.textBlock1.SetBinding(TextBlock.TextProperty, new Binding(".") { Source = myString });

在这里插入图片描述
二、DataContext作为Binding的源
我们这里先声明一个类

    public class Student
    {
        public int Id { get; set; }
        public int Age { get; set; }
    }

然后创建程序的UI

<Window x:Class="WpfApplication1.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:WpfApplication1"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="250" Width="359">
    <StackPanel Margin="0,0,0,0">
        <StackPanel.DataContext>
            <local:Student Age="11" Id="3" ></local:Student>
        </StackPanel.DataContext>
        <TextBlock Name="textBlock1">
            <TextBox Text="{Binding Age}"></TextBox>
            <TextBox Text="{Binding Id}"></TextBox>
        </TextBlock>
    </StackPanel>
</Window>

我们可以看下绑定后的结果
在这里插入图片描述

在UI元素的每个结点都有DataContext,当一个binding只知道自己的Path不知道自己的Source时,它会沿着UI元素树一路向树的根部寻找。

猜你喜欢

转载自blog.csdn.net/Maybe_ch/article/details/86478054