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 。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)