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; } } }
結(jié)果如下:

結(jié)論:如果沒有顯示給DataContext賦值,那么它會(huì)從父節(jié)點(diǎn)繼承。 并不是根據(jù)Path的屬性名來向上尋找對應(yīng)的DataContext。
經(jīng)調(diào)試發(fā)現(xiàn):四個(gè)TextBox的DataContext均為 teacher 。

浙公網(wǎng)安備 33010602011771號(hào)