C# Binding之 DataContext 测试
<Window x:Class="WpfApp2.BindingTest5" 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="BindingTest5" Height="135" Width="300"> <StackPanel Background="LightBlue" Name="sPanel1"> <!--<StackPanel.DataContext> <local:Student Id="6" Age="29" Name="Tim"/> </StackPanel.DataContext>--> <Grid x:Name="grid1"> <StackPanel> <TextBox x:Name="textBox1" Text="{Binding Id}"/> <TextBox x:Name="textBox2" Text="{Binding Name}"/> <TextBox x:Name="textBox3" Text="{Binding Age}"/> <TextBox x:Name="textBox4" Text="{Binding WorkYear}"/> </StackPanel> </Grid> </StackPanel> </Window> 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.Shapes; namespace WpfApp2 { /// <summary> /// BindingTest5.xaml 的交互逻辑 /// </summary> public partial class BindingTest5 : Window { public BindingTest5() { InitializeComponent(); Student student = new Student() { Age=100, Id=1, Name="Lucy"}; Teacher teacher=new Teacher() { WorkYear=20}; this.sPanel1.DataContext = student; this.grid1.DataContext = teacher; textBox1.BorderBrush = null; } } public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } public class Teacher { public int WorkYear { get; set; } } }
结果如下:
结论:如果没有显示给DataContext赋值,那么它会从父节点继承。 并不是根据Path的属性名来向上寻找对应的DataContext。
经调试发现:四个TextBox的DataContext均为 teacher 。