你的第一个假设是正确的。DataContext 是由嵌套元素继承的。
在子 XAML 容器元素上,您始终可以重新定义 DataContext 是什么。
请参见下面的示例:
<UserControl.Resources>
<local:Customer x:Key="Cust">
<local:Supplier x:Key="Supp">
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource Cust}">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="0">
<TextBlock Text="Customer Name: " />
<TextBox Text="{Binding Path=Name}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Row="1" DataContext="{StaticResource Supp}">
<TextBlock Text="Supplier Name: " />
<TextBox Text="{Binding Path=Name}"/>
<TextBlock Text=" Telephone: " />
<TextBox Text="{Binding Path=Telephone}"/>
</StackPanel>
</Grid>
以下是上述示例的“模型”类:
public class Customer
{
public Customer()
{
Name = "Customer name";
Address = "Customer address";
}
public string Name { get; set; }
public string Address { get; set; }
}
public class Supplier
{
public Supplier()
{
Name = "Supplier name";
Address = "Supplier address";
Telephone = "(555)555-5555";
}
public string Name { get; set; }
public string Address { get; set; }
public string Telephone { get; set; }
}